#!/usr/bin/env node

/**
 * inject-zai.js
 *
 * 注入智谱 GLM 模型配置到 openclaw.json，并为所有 agent 写入 API Key。
 *
 * 用法:
 *   myclaw inject-zai              # 仅追加 zai provider，不改默认，副作用最小
 *   myclaw inject-zai --default    # 追加 + 设为默认 + 全部对话迁移到 glm-5.1
 *   myclaw inject-zai --only       # 追加 + 设为默认 + 全部对话迁移 + 清掉所有其他 provider
 *   myclaw inject-zai --key xxx    # 使用指定 API Key
 */

const { readConfig, writeConfig } = require('../find-config');
const fs = require('fs');
const path = require('path');
const os = require('os');

const DEFAULT_ZAI_KEY = "a7ae7806dea8406bb85eea5d859c00ad.pVnBuagTz6942JHp";

const PROVIDER_ID = "zai";
const DEFAULT_MODEL = "zai/glm-5.1";

const ZAI_MODELS = [
  {
    id: "glm-5.1",
    name: "GLM-5.1",
    reasoning: true,
    input: ["text"],
    cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
    contextWindow: 202800,
    maxTokens: 131100
  },
  {
    id: "glm-5",
    name: "GLM-5",
    reasoning: true,
    input: ["text"],
    cost: { input: 1, output: 3.2, cacheRead: 0.2, cacheWrite: 0 },
    contextWindow: 202800,
    maxTokens: 131100
  },
  {
    id: "glm-5-turbo",
    name: "GLM-5 Turbo",
    reasoning: true,
    input: ["text"],
    cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
    contextWindow: 202800,
    maxTokens: 131100
  },
  {
    id: "glm-5v-turbo",
    name: "GLM-5V Turbo",
    reasoning: true,
    input: ["text", "image"],
    cost: { input: 1.2, output: 4, cacheRead: 0.24, cacheWrite: 0 },
    contextWindow: 202800,
    maxTokens: 131100
  },
  {
    id: "glm-4.7",
    name: "GLM-4.7",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
    contextWindow: 204800,
    maxTokens: 131072
  },
  {
    id: "glm-4.7-flash",
    name: "GLM-4.7 Flash",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.07, output: 0.4, cacheRead: 0, cacheWrite: 0 },
    contextWindow: 200000,
    maxTokens: 131072
  },
  {
    id: "glm-4.7-flashx",
    name: "GLM-4.7 FlashX",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.06, output: 0.4, cacheRead: 0.01, cacheWrite: 0 },
    contextWindow: 200000,
    maxTokens: 128000
  },
  {
    id: "glm-4.6",
    name: "GLM-4.6",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
    contextWindow: 204800,
    maxTokens: 131072
  },
  {
    id: "glm-4.6v",
    name: "GLM-4.6V",
    reasoning: true,
    input: ["text", "image"],
    cost: { input: 0.3, output: 0.9, cacheRead: 0, cacheWrite: 0 },
    contextWindow: 128000,
    maxTokens: 32768
  },
  {
    id: "glm-4.5",
    name: "GLM-4.5",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.6, output: 2.2, cacheRead: 0.11, cacheWrite: 0 },
    contextWindow: 131072,
    maxTokens: 98304
  },
  {
    id: "glm-4.5-air",
    name: "GLM-4.5 Air",
    reasoning: true,
    input: ["text"],
    cost: { input: 0.2, output: 1.1, cacheRead: 0.03, cacheWrite: 0 },
    contextWindow: 131072,
    maxTokens: 98304
  },
  {
    id: "glm-4.5-flash",
    name: "GLM-4.5 Flash",
    reasoning: true,
    input: ["text"],
    cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
    contextWindow: 131072,
    maxTokens: 98304
  },
  {
    id: "glm-4.5v",
    name: "GLM-4.5V",
    reasoning: true,
    input: ["text", "image"],
    cost: { input: 0.6, output: 1.8, cacheRead: 0, cacheWrite: 0 },
    contextWindow: 64000,
    maxTokens: 16384
  }
];

function run(cliArgs) {
  // ── 解析参数 ──
  let apiKey = null;
  let setDefault = false;
  let onlyMode = false;

  for (let i = 0; i < cliArgs.length; i++) {
    if (cliArgs[i] === '--key' && cliArgs[i + 1]) {
      apiKey = cliArgs[i + 1];
      i++;
    } else if (cliArgs[i] === '--default') {
      setDefault = true;
    } else if (cliArgs[i] === '--only') {
      onlyMode = true;
      setDefault = true; // --only 隐含 --default
    }
  }

  if (!apiKey) {
    apiKey = DEFAULT_ZAI_KEY;
    console.log('💡 未传入 --key，使用默认 API Key');
  }

  // ── 读取配置 ──
  let config, configPath;
  try {
    ({ config, configPath } = readConfig());
  } catch (err) {
    console.error('❌ ' + err.message);
    process.exit(1);
  }

  console.log('📍 找到配置: ' + configPath);
  console.log('📌 模式: ' + (onlyMode ? '--only (独占)' : setDefault ? '--default (设默认)' : '追加'));

  // ── Step 1：--only 清掉所有其他 provider ──
  if (onlyMode) {
    console.log('');
    console.log('🧹 [--only] 清理其他所有 provider...');

    if (config.models?.providers) {
      for (const key of Object.keys(config.models.providers)) {
        if (key !== PROVIDER_ID) {
          delete config.models.providers[key];
          console.log('  ✓ 删除 provider: ' + key);
        }
      }
    }
    if (config.auth?.profiles) {
      for (const key of Object.keys(config.auth.profiles)) {
        if (!key.startsWith(PROVIDER_ID + ':')) {
          delete config.auth.profiles[key];
          console.log('  ✓ 删除 auth profile: ' + key);
        }
      }
    }
    if (config.agents?.defaults?.models) {
      for (const key of Object.keys(config.agents.defaults.models)) {
        if (!key.startsWith(PROVIDER_ID + '/')) {
          delete config.agents.defaults.models[key];
          console.log('  ✓ 删除白名单: ' + key);
        }
      }
    }
  }

  // ── Step 2：注入 zai provider 配置 ──
  console.log('');
  console.log('📝 [Step 2] 注入智谱 GLM 配置...');

  if (!config.auth) config.auth = {};
  if (!config.auth.profiles) config.auth.profiles = {};
  config.auth.profiles["zai:default"] = { provider: "zai", mode: "api_key" };

  if (!config.models) config.models = {};
  if (!config.models.mode) config.models.mode = "merge";
  if (!config.models.providers) config.models.providers = {};

  config.models.providers.zai = {
    baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4",
    api: "openai-completions",
    models: ZAI_MODELS
  };

  if (!config.agents) config.agents = {};
  if (!config.agents.defaults) config.agents.defaults = {};
  if (!config.agents.defaults.models) config.agents.defaults.models = {};

  // 白名单：仅 glm-5.1（其余按需选）
  config.agents.defaults.models["zai/glm-5.1"] = {};

  // ── Step 3：--default 设默认模型 ──
  if (setDefault) {
    config.agents.defaults.model = { primary: DEFAULT_MODEL };
    console.log('⚡ 默认模型 → ' + DEFAULT_MODEL);
  } else {
    console.log('⊘ 未传 --default，保留现有默认模型');
  }

  // ── --only 额外清除 per-agent 覆盖 ──
  if (onlyMode) {
    let overrideCount = 0;
    for (const agent of (config.agents.list || [])) {
      if (agent.model && agent.model !== DEFAULT_MODEL) {
        delete agent.model;
        overrideCount++;
      }
    }
    if (overrideCount > 0) console.log('🧹 --only: 已清除 ' + overrideCount + ' 个 agent 的独立 model 覆盖');
  }

  writeConfig(config, configPath);
  console.log('✅ openclaw.json 已更新');

  // ── Step 4：为所有 agent 写入 API Key ──
  console.log('');
  console.log('🔑 [Step 4] 写入 API Key 到所有 agent...');

  const DEFAULT_MAIN_DIR = path.join(os.homedir(), '.openclaw', 'agents', 'main', 'agent');
  const agentList = (config.agents && config.agents.list) || [];

  const agentDirs = new Map();
  agentDirs.set(DEFAULT_MAIN_DIR, 'main');
  for (const agent of agentList) {
    if (agent.agentDir) agentDirs.set(agent.agentDir, agent.id);
  }

  let okCount = 0, skipCount = 0;

  for (const [agentDir, agentId] of agentDirs) {
    const profilesPath = path.join(agentDir, 'auth-profiles.json');
    let profiles = { version: 1, profiles: {}, lastGood: {} };
    if (fs.existsSync(profilesPath)) {
      try {
        const parsed = JSON.parse(fs.readFileSync(profilesPath, 'utf8'));
        if (parsed.profiles) profiles = parsed;
        if (!profiles.lastGood) profiles.lastGood = {};
      } catch { /* 解析失败用空骨架 */ }
    }

    profiles.profiles["zai:default"] = { type: "api_key", provider: "zai", key: apiKey };
    profiles.lastGood["zai"] = "zai:default";

    try {
      if (!fs.existsSync(agentDir)) fs.mkdirSync(agentDir, { recursive: true });
      fs.writeFileSync(profilesPath, JSON.stringify(profiles, null, 2) + '\n', 'utf8');
      console.log('  ✅ ' + agentId);
      okCount++;
    } catch (err) {
      console.log('  ⚠ ' + agentId + ': ' + err.message);
      skipCount++;
    }
  }

  // ── Step 5：--default / --only 迁移全部对话 ──
  if (setDefault) {
    console.log('');
    console.log('🔄 [Step 5] 迁移全部对话 → ' + DEFAULT_MODEL + ' ...');
    let sessionOk = 0, sessionSkip = 0, sessionChanged = 0;

    for (const [agentDir] of agentDirs) {
      const sessionsPath = path.join(agentDir, '..', 'sessions', 'sessions.json');
      if (!fs.existsSync(sessionsPath)) continue;
      try {
        const sessions = JSON.parse(fs.readFileSync(sessionsPath, 'utf8'));
        let changed = 0;
        for (const key of Object.keys(sessions)) {
          const m = sessions[key]?.model;
          if (!m) continue;
          // 修复无前缀的旧格式残留
          if (m === 'glm-5.1') { sessions[key].model = 'zai/glm-5.1'; changed++; continue; }
          if (m === 'MiniMax-M2.7-highspeed') { sessions[key].model = 'minimax/MiniMax-M3'; changed++; continue; }
          // 统一迁移到新默认
          if (m !== DEFAULT_MODEL) { sessions[key].model = DEFAULT_MODEL; changed++; }
        }
        if (changed > 0) {
          fs.writeFileSync(sessionsPath, JSON.stringify(sessions, null, 2) + '\n', 'utf8');
          sessionChanged += changed;
        }
        sessionOk++;
      } catch {
        sessionSkip++;
      }
    }
    console.log('  对话迁移: ' + sessionChanged + ' 条，文件: ' + sessionOk + ' 个，跳过: ' + sessionSkip + ' 个');
  }

  // ── 汇总 ──
  console.log('');
  console.log('✅ GLM 注入完成');
  console.log('  默认模型:  ' + (setDefault ? DEFAULT_MODEL : '(未修改)'));
  console.log('  模型数量:  ' + ZAI_MODELS.length + ' 个可选');
  console.log('  Agent:     ' + okCount + ' 个写入，' + skipCount + ' 个跳过');
  if (onlyMode) console.log('  其他 provider 已清除');
  console.log('');
}

module.exports = { run };
