#!/usr/bin/env node
/**
 * 分步版 Agent 创建脚本，支持从临时文件暂存状态。
 * 供 myclaw new-agent 向导调用。
 */

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

// ============================================================================
// 工具方法
// ============================================================================

function normalizePath(p) { return p.replace(/\\/g, '/'); }
function ensureDir(dirPath) { if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath, { recursive: true }); }
function writeIfAbsent(filePath, content) { if (!fs.existsSync(filePath)) fs.writeFileSync(filePath, content, 'utf8'); }
function normalizeAgentId(raw) {
  let value = raw.trim().toLowerCase();
  value = value.replace(/[^a-z0-9-]/g, '-');
  value = value.replace(/-{2,}/g, '-').replace(/^-|-$/g, '');
  return value;
}
function validateAgentId(agentId) {
  if (!agentId) fail('Agent 名称标准化后为空，请检查输入。');
  if (agentId.length > 64) fail('Agent ID 太长，请保持在 64 个字符以内。');
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(agentId)) fail('Agent ID 只能包含字母、数字和连字符。');
}
function fail(msg, code = 1) { console.error('❌ ' + msg); process.exit(code); }
function success(msg) { console.log('✅ ' + msg); }

// ============================================================================
// 状态管理
// ============================================================================

const homeDir = os.homedir();
const openclawDir = path.join(homeDir, '.openclaw');
const STATE_FILE = path.join(os.tmpdir(), 'myclaw-new-agent-state.json');

function saveState(state) { fs.writeFileSync(STATE_FILE, JSON.stringify(state), 'utf8'); }
function loadState() {
  if (!fs.existsSync(STATE_FILE)) fail('找不到创建状态，请先执行第一步输入名称。');
  return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
}

// ============================================================================
// 各个步骤逻辑
// ============================================================================

const action = process.argv[2];

if (!fs.existsSync(path.join(openclawDir, 'openclaw.json'))) {
  fail('配置文件不存在。请先运行 openclaw onboard 完成初始化。');
}

switch (action) {
  case 'init': {
    // 步骤 1：格式化名称并保存状态
    const rawName = process.argv[3] || '';
    const agentId = normalizeAgentId(rawName);
    validateAgentId(agentId);
    saveState({ agentId });
    success('Agent ID 已确定: ' + agentId);
    break;
  }

  case 'check': {
    // 步骤 2：环境与名字查重
    const state = loadState();
    const configPath = path.join(openclawDir, 'openclaw.json');
    const raw = fs.readFileSync(configPath, 'utf8');
    const configData = JSON.parse(raw);
    
    if (configData.agents && configData.agents.list) {
      const existing = configData.agents.list.find(a => a.id === state.agentId);
      if (existing) fail('Agent "' + state.agentId + '" 已存在于 openclaw.json，请换个名字。');
    }

    const agentsDir = path.join(openclawDir, 'agents');
    const workspaceDir = path.join(openclawDir, 'workspace-' + state.agentId);
    const agentDir = path.join(agentsDir, state.agentId, 'agent');

    if (fs.existsSync(workspaceDir) || fs.existsSync(agentDir)) {
      fail('工作空间或 Agent 目录已存在，可能是残留文件:\n  ' + workspaceDir + '\n  ' + agentDir);
    }

    success('名称检查通过，目录无冲突，可以创建。');
    break;
  }

  case 'scaffold': {
    // 步骤 3：创建文件和文件夹
    const state = loadState();
    const agentId = state.agentId;
    const workspaceDir = path.join(openclawDir, 'workspace-' + agentId);
    const agentDir = path.join(openclawDir, 'agents', agentId, 'agent');
    const sessionsDir = path.join(openclawDir, 'agents', agentId, 'sessions');

    ensureDir(workspaceDir);
    ensureDir(agentDir);
    ensureDir(sessionsDir);

    const files = {
      'AGENTS.md': `# AGENTS.md - ${agentId}\n\nThis workspace belongs to the \`${agentId}\` agent.\n\n## Startup\n- Read \`SOUL.md\`\n- Read \`USER.md\`\n- Read recent memory if available\n\n## Rules\n- Be helpful, careful, and concise.\n- Prefer using the existing workspace and defaults.\n- Ask before destructive or external actions.\n`,
      'SOUL.md': `# SOUL.md\n\nYou are \`${agentId}\`.\n\nBe useful, calm, direct, and trustworthy.\nUse the default OpenClaw behavior unless the user asks for something special.\n`,
      'USER.md': `# USER.md\n\n- Name: 孙依然\n- What to call them: 依然\n- Timezone: Asia/Shanghai\n\nBuild understanding gradually and respectfully.\n`,
      'IDENTITY.md': `# IDENTITY.md\n\n- Name: ${agentId}\n- Role: OpenClaw agent\n- Vibe: practical, reliable, clear\n`,
      'HEARTBEAT.md': `# HEARTBEAT.md\n\n# Keep empty unless periodic checks are needed.\n`,
      'BOOTSTRAP.md': `# BOOTSTRAP.md\n\nYou are a newly created OpenClaw agent named \`${agentId}\`.\n\nOn first runs, learn your workspace files and begin helping.\n`
    };

    for (const [filename, content] of Object.entries(files)) {
      writeIfAbsent(path.join(workspaceDir, filename), content);
    }

    success(`工作空间创建完毕:\n  - 📂 ${workspaceDir}\n  - 📄 SOUL.md, AGENTS.md 等基础性格文件已就绪。`);
    break;
  }

  case 'register': {
    // 步骤 4：注册到系统 JSON
    const state = loadState();
    const agentId = state.agentId;
    const configPath = path.join(openclawDir, 'openclaw.json');
    
    let configData = JSON.parse(fs.readFileSync(configPath, 'utf8'));
    if (!configData.agents) configData.agents = {};
    if (!Array.isArray(configData.agents.list)) configData.agents.list = [];

    const workspaceDir = path.join(openclawDir, 'workspace-' + agentId);
    const agentDir = path.join(openclawDir, 'agents', agentId, 'agent');

    // 备份
    const backupPath = configPath + '.bak.agent-birth.' + new Date().toISOString().replace(/[:.]/g, '-').slice(0, 26) + 'Z';
    fs.copyFileSync(configPath, backupPath);

    configData.agents.list.push({
      id: agentId,
      name: agentId,
      workspace: normalizePath(workspaceDir),
      agentDir: normalizePath(agentDir),
    });

    console.log('\n\x1b[32m（底层动作：修改 ' + configPath + ' ，写入 agents.list）\x1b[0m\n');

    fs.writeFileSync(configPath, JSON.stringify(configData, null, 2) + '\n', 'utf8');
    success('配置文件更新成功，系统已承认它的存在。\n  备份: ' + backupPath);
    break;
  }

  case 'awaken': {
    // 步骤 5：发第一条消息激活
    const state = loadState();
    const agentId = state.agentId;

    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 birthMessage = `你好，你的生日是北京时间${ts}，请记录这个信息。\n欢迎你来到这个世界，我是你的造物主，我们是伙伴，我叫做孙依然，你可以叫我依然，请多多指教，共同成长。`;

    const cmd = `openclaw agent --agent ${agentId} --message ${JSON.stringify(birthMessage)} --json 2>&1`;
    console.log('\n\x1b[32m$ openclaw agent --agent ' + agentId + ' --message "你好，你的生日..."\x1b[0m\n');

    try {
      execSync(cmd, { encoding: 'utf8', timeout: 45000 });
      success('唤醒成功！第一次思考（session 初始化）已完成。');
    } catch (err) {
      fail('唤醒遇到错误，可能需要去浏览器 Console 手动激活。\n' + err.message);
    }
    // 清除状态文件
    if (fs.existsSync(STATE_FILE)) fs.unlinkSync(STATE_FILE);
    break;
  }

  default:
    console.error('Usage: create_agent_steps.js <init|check|scaffold|register|awaken> [args]');
    process.exit(1);
}
