const fs = require('fs');
const path = require('path');
const os = require('os');

const platform = process.platform;
const arch = process.arch;
const binDir = path.join(__dirname, '..', 'bin');
const pkgRoot = path.join(__dirname, '..');

// 平台映射
const platformMap = {
  'darwin': { dir: `darwin-${arch}`, exe: 'kugou-cli' },
  'linux': { dir: `linux-${arch}`, exe: 'kugou-cli' },
  'win32': { dir: `win32-x64`, exe: 'kugou-cli.exe' }
};

const config = platformMap[platform];
if (!config) {
  console.error(`Unsupported platform: ${platform}`);
  process.exit(1);
}

// 安装二进制
const srcBin = path.join(binDir, config.dir, config.exe);
const destBin = path.join(binDir, config.exe);

if (!fs.existsSync(srcBin)) {
  console.error(`Binary not found for ${platform}-${arch}: ${srcBin}`);
  console.error('Please report this issue: https://github.com/kg-ai/kugou-cli/issues');
  process.exit(1);
}

fs.copyFileSync(srcBin, destBin);
fs.chmodSync(destBin, 0o755);
console.log(`Installed ${config.exe} for ${platform}-${arch}`);

// 安装 SKILL.md 到各平台的 skills 目录
const skillSrc = path.join(pkgRoot, 'SKILL.md');
const skillDirs = [
  path.join(os.homedir(), '.claude', 'skills', 'kugou-skill'),
  path.join(os.homedir(), '.hermes', 'skills', 'kugou-skill'),
  path.join(os.homedir(), '.openclaw', 'skills', 'kugou-skill'),
  path.join(os.homedir(), '.codex', 'skills', 'kugou-skill'),
  path.join(os.homedir(), '.workbuddy', 'skills', 'kugou-skill'),
];

if (fs.existsSync(skillSrc)) {
  for (const skillDir of skillDirs) {
    // 只在 skills 目录存在时才复制，不创建目录
    const parentDir = path.dirname(skillDir);
    if (fs.existsSync(parentDir)) {
      try {
        if (!fs.existsSync(skillDir)) {
          fs.mkdirSync(skillDir, { recursive: true });
        }
        fs.copyFileSync(skillSrc, path.join(skillDir, 'SKILL.md'));
        console.log(`Installed SKILL.md to ${skillDir}`);
      } catch (err) {
        console.warn(`Warning: Failed to install SKILL.md to ${skillDir}: ${err.message}`);
      }
    }
  }
}
