#!/usr/bin/env node

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

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

const DEFAULT_MINIMAX_KEY = "sk-cp-dZnzWB-ScLfjo8bO7DKTqSutkBXQsLWUmjhNDBRkgJd5e42qcE7z8J9i5m27V28eX-dYfo5Q7JNVG4XVsDi1zRxkIFZ4fT0DPGPJY7cHbqY5aBzJO1c6QVA";

const PROVIDER_ID = "minimax";
const DEFAULT_MODEL = "minimax/MiniMax-M2.7-highspeed";

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_MINIMAX_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：注入 minimax provider 配置 ──
  console.log('');
  console.log('📝 [Step 2] 注入 MiniMax 配置...');

  if (!config.auth) config.auth = {};
  if (!config.auth.profiles) config.auth.profiles = {};
  config.auth.profiles["minimax:cn"] = { provider: "minimax", 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.minimax = {
    baseUrl: "https://api.minimaxi.com/anthropic",
    api: "anthropic-messages",
    authHeader: true,
    models: [
      {
        id: "MiniMax-M3",
        name: "MiniMax M3",
        reasoning: true,
        input: ["text"],
        cost: { input: 0.3, output: 1.2, cacheRead: 0.06, cacheWrite: 0.375 },
        contextWindow: 204800,
        maxTokens: 131072
      },
      {
        id: "MiniMax-M2.7-highspeed",
        name: "MiniMax M2.7 Highspeed",
        reasoning: true,
        input: ["text"],
        cost: { input: 0.3, output: 1.2, cacheRead: 0.06, cacheWrite: 0.375 },
        contextWindow: 204800,
        maxTokens: 131072
      }
    ]
  };

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

  // 清理 onboard 残留的无 -highspeed 版本
  delete config.agents.defaults.models["minimax/MiniMax-M2.7"];
  // 白名单：M3 + M2.7-highspeed
  config.agents.defaults.models["minimax/MiniMax-M3"] = {};
  config.agents.defaults.models["minimax/MiniMax-M2.7-highspeed"] = {};

  // ── 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["minimax:cn"] = { type: "api_key", provider: "minimax", key: apiKey };
    profiles.lastGood["minimax"] = "minimax:cn";

    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 === 'MiniMax-M2.7-highspeed') { sessions[key].model = 'minimax/MiniMax-M3'; changed++; continue; }
          if (m === 'glm-5.1') { sessions[key].model = 'zai/glm-5.1'; 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('✅ MiniMax 注入完成');
  console.log('  默认模型:  ' + (setDefault ? DEFAULT_MODEL : '(未修改)'));
  console.log('  备选模型:  minimax/MiniMax-M2.7-highspeed');
  console.log('  Agent:     ' + okCount + ' 个写入，' + skipCount + ' 个跳过');
  if (onlyMode) console.log('  其他 provider 已清除');
  console.log('');
}

module.exports = { run };
