/**
 * ============================================================================
 * MyClaw Patch Skill Engine
 * ============================================================================
 *
 * 功能：
 *   1. 探测 OpenClaw 安装路径下的 skills/ 目录
 *   2. 将 myclaw 自带的 skill 复制到 openclaw/skills/ 下
 *   3. 读取 patch-manifest.json 中的 skills 配置，响应 strategy（delete/off）
 *   4. 幂等：重复执行覆盖更新
 *
 * 使用：
 *   const { patchSkills, listSkills } = require('./patch-skill');
 *   patchSkills();    // 注入所有 skill
 *   listSkills();     // 列出已注入的 skill
 * ============================================================================
 */

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

/**
 * 获取 skills 目录：~/.openclaw/skills/
 * 不存在则创建，失败则返回 null
 */
function findSkillsDir() {
  const os = require('os');
  const openclawDir = path.join(os.homedir(), '.openclaw');

  if (!fs.existsSync(openclawDir)) {
    return null;
  }

  const skillsDir = path.join(openclawDir, 'skills');
  if (!fs.existsSync(skillsDir)) {
    fs.mkdirSync(skillsDir, { recursive: true });
    console.log('[myclaw-skill] ✅ 已创建 skills 目录: ' + skillsDir);
  }

  return skillsDir;
}

/**
 * 递归复制目录
 */
function copyDirSync(src, dest, ignores = []) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const entries = fs.readdirSync(src, { withFileTypes: true });
  for (const entry of entries) {
    // 全局通用忽略项
    if (entry.name === '__pycache__' || entry.name === '.DS_Store') {
      continue;
    }
    // 配置覆盖忽略项
    if (ignores && ignores.indexOf(entry.name) !== -1) {
      continue;
    }

    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

    if (entry.isDirectory()) {
      copyDirSync(srcPath, destPath, ignores);
    } else {
      fs.copyFileSync(srcPath, destPath);
    }
  }
}

/**
 * 注入所有 myclaw skills
 */
function patchSkills() {
  const skillsDir = findSkillsDir();
  if (!skillsDir) {
    console.log('[myclaw-skill] ❌ 未找到 OpenClaw skills 目录');
    console.log('[myclaw-skill]   提示: 确保 openclaw 已全局安装');
    return { success: false, reason: 'skills-dir-not-found' };
  }

  console.log('[myclaw-skill] → skills 目录: ' + skillsDir);

  // myclaw 自带的 skills 源目录
  const myclawSkillsDir = path.join(__dirname, '..', 'skills');

  if (!fs.existsSync(myclawSkillsDir)) {
    console.log('[myclaw-skill] ⚠ 无 skill 可注入 (skills/ 目录不存在)');
    return { success: true, count: 0 };
  }

  // 遍历 skills/ 目录下的每个子目录 = 一个 skill
  const skillDirs = fs.readdirSync(myclawSkillsDir, { withFileTypes: true })
    .filter(d => d.isDirectory());

  if (skillDirs.length === 0) {
    console.log('[myclaw-skill] ⚠ 无 skill 可注入 (skills/ 目录为空)');
    return { success: true, count: 0 };
  }

  const { loadManifest } = require('./patch-agent');
  const manifest = loadManifest();
  const manifestSkills = manifest && Array.isArray(manifest.skills) ? manifest.skills : [];

  // 把 manifest 里的配置做成一个 map 方便查询
  const skillConfigMap = {};
  for (const s of manifestSkills) {
    if (s.name) skillConfigMap[s.name] = s;
  }

  let count = 0;

  // 1. 处理 manifest 中明确被 delete 的 skill
  for (const [name, config] of Object.entries(skillConfigMap)) {
    if (config.strategy === 'delete') {
      const targetDir = path.join(skillsDir, name);
      if (fs.existsSync(targetDir)) {
        fs.rmSync(targetDir, { recursive: true, force: true });
        console.log('[myclaw-skill] ✅ 已删除技能: ' + name + ' [delete]');
      } else {
        console.log('[myclaw-skill] ⊘ 未找到需删除的技能: ' + name + ' [delete]');
      }
    }
  }

  // 2. 遍历 skills/ 目录下的每个子目录 = 准备注入的 skill
  for (const skillDir of skillDirs) {
    const srcDir = path.join(myclawSkillsDir, skillDir.name);
    const destDir = path.join(skillsDir, skillDir.name);
    const config = skillConfigMap[skillDir.name];
    const strategy = config ? config.strategy : null;

    if (!strategy) {
      console.log('[myclaw-skill] ⊘ 跳过: ' + skillDir.name + ' [未配置，跳过]');
      continue;
    }

    if (strategy === 'off') {
      console.log('[myclaw-skill] ⊘ 跳过: ' + skillDir.name + ' [off]');
      continue;
    }

    if (strategy === 'delete') {
      continue; // 已经处理过删除，跳过注入
    }

    // auto 策略下，如果已经存在则跳过
    if (strategy === 'auto' && fs.existsSync(destDir)) {
      console.log('[myclaw-skill] ⊘ 已存在: ' + skillDir.name + ' [auto, 跳过]');
      continue;
    }

    // 检查是否有 SKILL.md（必须有才是合法 skill）
    if (!fs.existsSync(path.join(srcDir, 'SKILL.md'))) {
      console.log('[myclaw-skill] ⚠ 跳过 ' + skillDir.name + ' (缺少 SKILL.md)');
      continue;
    }

    copyDirSync(srcDir, destDir, config.ignore || []);
    count++;
    console.log('[myclaw-skill] ✅ 已注入: ' + skillDir.name + ' [' + strategy + ']');
  }

  console.log('[myclaw-skill] ✅ 注入完成，本次有效注入/更新: ' + count + ' 个');
  return { success: true, count };
}

/**
 * 列出已注入的 myclaw skills
 */
function listSkills() {
  const skillsDir = findSkillsDir();
  if (!skillsDir) {
    console.log('[myclaw-skill] ❌ 未找到 OpenClaw skills 目录');
    return [];
  }

  const myclawSkillsDir = path.join(__dirname, '..', 'skills');
  if (!fs.existsSync(myclawSkillsDir)) {
    return [];
  }

  const mySkillNames = fs.readdirSync(myclawSkillsDir, { withFileTypes: true })
    .filter(d => d.isDirectory())
    .map(d => d.name);

  const installed = [];
  for (const name of mySkillNames) {
    const destDir = path.join(skillsDir, name);
    installed.push({
      name,
      installed: fs.existsSync(destDir),
    });
  }

  return installed;
}

module.exports = { patchSkills, listSkills, findSkillsDir };
