/**
 * ============================================================================
 * MyClaw Patch Agent Engine - 智能体上传
 * ============================================================================
 *
 * 功能：
 *   1. 读取 patch-manifest.json 中的 agents 列表
 *   2. 根据 strategy 决定行为：
 *      - auto:       目标 workspace 不存在时才注入（默认）
 *      - on:         始终覆盖更新 workspace 文件
 *      - delete:     彻底删除该智能体（配置、目录）
 *      - off:        跳过，不注入
 *   3. 将 workspace 复制到 ~/.openclaw/ 下
 *   4. 在 openclaw.json 的 agents.list 中注册
 *   5. 创建 agent 目录结构
 *
 * ============================================================================
 */

const fs = require('fs');
const path = require('path');
const os = require('os');
const { execSync } = require('child_process');

/**
 * 递归复制目录（幂等覆盖）
 */
function copyDirSync(src, dest) {
  if (!fs.existsSync(dest)) {
    fs.mkdirSync(dest, { recursive: true });
  }

  const entries = fs.readdirSync(src, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = path.join(src, entry.name);
    const destPath = path.join(dest, entry.name);

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

/**
 * 加载 manifest
 */
function loadManifest() {
  const manifestPath = path.join(__dirname, 'patch-manifest.json');
  if (!fs.existsSync(manifestPath)) {
    return null;
  }
  return JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
}

/**
 * 注入所有预打包智能体
 */
function patchAgents() {
  const openclawDir = path.join(os.homedir(), '.openclaw');
  const configPath = path.join(openclawDir, 'openclaw.json');

  // 检查 openclaw 是否已初始化
  if (!fs.existsSync(configPath)) {
    console.log('[myclaw-agent] ❌ 未找到 openclaw.json');
    console.log('[myclaw-agent]   提示: 请先运行 openclaw onboard 完成初始化');
    return { success: false, reason: 'config-not-found' };
  }

  // 加载 manifest
  const manifest = loadManifest();
  if (!manifest || !Array.isArray(manifest.agents) || manifest.agents.length === 0) {
    console.log('[myclaw-agent] ⚠ 无智能体可上传 (manifest 为空或无 agents)');
    return { success: true, count: 0 };
  }

  // 加载配置
  let configData;
  try {
    const raw = fs.readFileSync(configPath, 'utf8');
    configData = JSON.parse(raw);
  } catch (err) {
    console.log('[myclaw-agent] ❌ openclaw.json 读取失败: ' + err.message);
    return { success: false, reason: 'config-read-error' };
  }

  // 确保 agents 结构存在
  if (!configData.agents) {
    configData.agents = {};
  }
  if (!Array.isArray(configData.agents.list)) {
    configData.agents.list = [];
  }

  // 已注册的 agent ID 集合
  const existingIds = new Set(
    configData.agents.list
      .filter(e => e && typeof e === 'object')
      .map(e => e.id)
  );

  const agentListDir = path.join(__dirname, '..', 'agent-list');

  console.log('[myclaw-agent] → Manifest: ' + manifest.agents.length + ' 个智能体');

  let uploaded = 0;
  let updated = 0;
  let skipped = 0;
  let configChanged = false;

  for (const entry of manifest.agents) {
    const agentId = entry.id;
    const workspaceName = entry.workspace || ('workspace-' + agentId);
    const strategy = entry.strategy || 'auto';
    const desc = entry.description || agentId;

    const destWorkspace = path.join(openclawDir, workspaceName);
    const agentDir = path.join(openclawDir, 'agents', agentId, 'agent');
    const agentsDirBase = path.join(openclawDir, 'agents', agentId);

    // off → 跳过
    if (strategy === 'off') {
      console.log('[myclaw-agent] ⊘ 跳过: ' + agentId + ' (' + desc + ') [off]');
      skipped++;
      continue;
    }

    // delete → 彻底移除
    if (strategy === 'delete') {
      let deleted = false;
      if (fs.existsSync(destWorkspace)) {
        fs.rmSync(destWorkspace, { recursive: true, force: true });
        deleted = true;
      }
      if (fs.existsSync(agentsDirBase)) {
        fs.rmSync(agentsDirBase, { recursive: true, force: true });
        deleted = true;
      }
      if (existingIds.has(agentId)) {
        configData.agents.list = configData.agents.list.filter(e => e.id !== agentId);
        existingIds.delete(agentId);
        configChanged = true;
        deleted = true;
      }
      if (deleted) {
        console.log('[myclaw-agent] ✅ 已删除: ' + agentId + ' (' + desc + ') [delete]');
      } else {
        console.log('[myclaw-agent] ⊘ 未找到需删除的: ' + agentId + ' (' + desc + ') [delete]');
      }
      skipped++;
      continue;
    }

    const srcWorkspace = path.join(agentListDir, workspaceName);

    // 检查源文件是否存在
    if (!fs.existsSync(srcWorkspace)) {
      console.log('[myclaw-agent] ⚠ 源目录不存在: ' + workspaceName + '，跳过');
      skipped++;
      continue;
    }

    const alreadyExists = fs.existsSync(destWorkspace);

    // auto → 已存在则跳过文件复制，但仍需检查 sessions
    if (strategy !== 'auto' || !alreadyExists) {
      copyDirSync(srcWorkspace, destWorkspace);
    } else {
      console.log('[myclaw-agent] ⊘ 已存在: ' + agentId + ' (' + desc + ') [auto, 跳过复制]');
      skipped++;
    }

    // 确保 agent 目录结构存在
    if (!fs.existsSync(agentDir)) {
      fs.mkdirSync(agentDir, { recursive: true });
    }
    const sessionsDir = path.join(openclawDir, 'agents', agentId, 'sessions');
    if (!fs.existsSync(sessionsDir)) {
      fs.mkdirSync(sessionsDir, { recursive: true });
    }

    // 注册到 openclaw.json
    if (!existingIds.has(agentId)) {
      configData.agents.list.push({
        id: agentId,
        name: agentId,
        workspace: destWorkspace,
        agentDir: agentDir,
      });
      existingIds.add(agentId);
      configChanged = true;
      uploaded++;
      console.log('[myclaw-agent] ✅ 已上传并注册: ' + agentId + ' (' + desc + ') [' + strategy + ']');

      // 自动发送出生消息，创建首个 session
      try {
        const nowUtc = new Date();
        const nowBj = new Date(nowUtc.getTime() + 8 * 60 * 60 * 1000);
        const ts = nowBj.getUTCFullYear() + '年' + (nowBj.getUTCMonth() + 1) + '月' + nowBj.getUTCDate() + '日' + String(nowBj.getUTCHours()).padStart(2, '0') + ':' + String(nowBj.getUTCMinutes()).padStart(2, '0');
        const birthMsg = '你好，现在是北京时间' + ts;
        const birthCmd = 'openclaw agent --agent ' + agentId + ' --message ' + JSON.stringify(birthMsg) + ' --json';
        console.log('[myclaw-agent] → 发送出生消息: ' + agentId + ' ...');
        execSync(birthCmd + ' 2>&1', { encoding: 'utf8', timeout: 45000 });
        console.log('[myclaw-agent] ✅ 出生消息已发送: ' + agentId);
      } catch (birthErr) {
        console.log('[myclaw-agent] ⚠ 出生消息发送失败（非致命）: ' + (birthErr.message || birthErr));
      }
    } else if (alreadyExists) {
      updated++;
      console.log('[myclaw-agent] ✅ 已覆盖更新: ' + agentId + ' (' + desc + ') [' + strategy + ']');

      // sessions 为空 → 补发出生消息（agent 存在但从未激活）
      {
        const sessionFiles = fs.readdirSync(sessionsDir).filter(f => !f.startsWith('.'));
        if (sessionFiles.length === 0) {
          try {
            const nowUtc = new Date();
            const nowBj = new Date(nowUtc.getTime() + 8 * 60 * 60 * 1000);
            const ts = nowBj.getUTCFullYear() + '年' + (nowBj.getUTCMonth() + 1) + '月' + nowBj.getUTCDate() + '日' + String(nowBj.getUTCHours()).padStart(2, '0') + ':' + String(nowBj.getUTCMinutes()).padStart(2, '0');
            const birthMsg = '你好，现在是北京时间' + ts;
            const birthCmd = 'openclaw agent --agent ' + agentId + ' --message ' + JSON.stringify(birthMsg) + ' --json';
            console.log('[myclaw-agent] → sessions 为空，补发出生消息: ' + agentId + ' ...');
            execSync(birthCmd + ' 2>&1', { encoding: 'utf8', timeout: 45000 });
            console.log('[myclaw-agent] ✅ 出生消息已发送: ' + agentId);
          } catch (birthErr) {
            console.log('[myclaw-agent] ⚠ 出生消息发送失败（非致命）: ' + (birthErr.message || birthErr));
          }
        }
      }
    } else {
      updated++;
      console.log('[myclaw-agent] ✅ 已更新: ' + agentId + ' (' + desc + ')');
    }
  }

  // 写回配置文件
  if (configChanged) {
    try {
      fs.writeFileSync(configPath, JSON.stringify(configData, null, 2) + '\n', 'utf8');
      console.log('[myclaw-agent] ✅ openclaw.json 已更新');
    } catch (err) {
      console.log('[myclaw-agent] ❌ openclaw.json 写入失败: ' + err.message);
      return { success: false, reason: 'config-write-error' };
    }
  }

  console.log('[myclaw-agent] ✅ 智能体上传完成: ' + uploaded + ' 新建, ' + updated + ' 更新, ' + skipped + ' 跳过');
  return { success: true, uploaded, updated, skipped, total: uploaded + updated };
}

/**
 * 列出 manifest 中所有智能体及状态
 */
function listAgents() {
  const openclawDir = path.join(os.homedir(), '.openclaw');
  const manifest = loadManifest();

  if (!manifest || !Array.isArray(manifest.agents)) {
    return [];
  }

  return manifest.agents.map(entry => {
    const workspaceName = entry.workspace || ('workspace-' + entry.id);
    const destWorkspace = path.join(openclawDir, workspaceName);
    return {
      id: entry.id,
      description: entry.description || entry.id,
      strategy: entry.strategy || 'if-absent',
      installed: fs.existsSync(destWorkspace),
    };
  });
}

module.exports = { patchAgents, listAgents, loadManifest };
