#!/usr/bin/env node

/**
 * inject-zai.js
 *
 * 增量注入智谱 GLM 模型配置到 openclaw.json，不影响已有的其他 provider。
 * 同时写入 API Key 到 auth-profiles.json。
 *
 * 流程:
 *   1. 写入 API Key 到 auth-profiles.json
 *   2. 增量写入 zai provider + 白名单 + 默认聊天模型
 *
 * 入口: myclaw zai [--key xxx]
 */

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

// ============================================================
// 默认智谱 API Key
// ============================================================
const DEFAULT_ZAI_KEY = "122435800204471f83045b53aaf5c54e.StwsrQVMlYXkLcJ1";

// 智谱模型列表
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 forceClean = false;

  for (let i = 0; i < cliArgs.length; i++) {
    if (cliArgs[i] === '--key' && cliArgs[i + 1]) {
      apiKey = cliArgs[i + 1];
      i++;
    }
    if (cliArgs[i] === '-f' || cliArgs[i] === '--force') {
      forceClean = true;
    }
  }

  // 如果没有传参数，使用默认 Key
  if (!apiKey && DEFAULT_ZAI_KEY) {
    apiKey = DEFAULT_ZAI_KEY;
    console.log('💡 未传入 --key 参数，自动使用默认的 API Key');
  }

  // 如果启用了强制清理模式
  if (forceClean) {
    console.log('');
    console.log('🧹 [强制清理] 清理其他大模型配置...');
    // 清理 minimax provider
    if (config.models?.providers?.minimax) {
      delete config.models.providers.minimax;
      console.log('  ✓ 已删除 models.providers.minimax');
    }
    // 清理 minimax auth profile
    if (config.auth?.profiles?.['minimax:cn']) {
      delete config.auth.profiles['minimax:cn'];
      console.log('  ✓ 已删除 auth.profiles["minimax:cn"]');
    }
    // 清理 minimax 白名单模型
    if (config.agents?.defaults?.models) {
      const minimaxKeys = Object.keys(config.agents.defaults.models).filter(k => k.startsWith('minimax/'));
      for (const key of minimaxKeys) {
        delete config.agents.defaults.models[key];
        console.log('  ✓ 已删除 agents.defaults.models["' + key + '"]');
      }
    }
    // 如果默认模型是 minimax，清除它
    if (config.agents?.defaults?.model?.primary?.startsWith('minimax/')) {
      delete config.agents.defaults.model;
      console.log('  ✓ 已清除默认模型 (原为 minimax)');
    }
    // 如果图片模型是 minimax，清除它
    if (config.agents?.defaults?.imageGenerationModel?.primary?.startsWith('minimax/')) {
      delete config.agents.defaults.imageGenerationModel;
      console.log('  ✓ 已删除 agents.defaults.imageGenerationModel');
    }
  }

  // 查找配置
  let configPath;
  try {
    ({ configPath } = readConfig());
  } catch (err) {
    console.error('❌ ' + err.message);
    process.exit(1);
  }

  console.log('📍 找到配置: ' + configPath);

  // ============================================================
  // 第一步：写入 API Key 到 auth-profiles.json
  // ============================================================

  console.log('');
  console.log('🔑 [Step 1] 写入智谱 API Key 到 auth-profiles.json...');

  const authProfilePath = path.join(os.homedir(), '.openclaw', 'agents', 'main', 'agent', 'auth-profiles.json');
  let authProfiles = {};

  if (fs.existsSync(authProfilePath)) {
    try {
      authProfiles = JSON.parse(fs.readFileSync(authProfilePath, 'utf8'));
    } catch {
      authProfiles = {};
    }
  }

  if (!authProfiles.profiles) authProfiles.profiles = {};
  if (!authProfiles.lastGood) authProfiles.lastGood = {};

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

  // 确保目录存在
  const authDir = path.dirname(authProfilePath);
  if (!fs.existsSync(authDir)) {
    fs.mkdirSync(authDir, { recursive: true });
  }

  fs.writeFileSync(authProfilePath, JSON.stringify(authProfiles, null, 2) + '\n', 'utf8');
  console.log('  ✅ API Key 已写入');

  // ============================================================
  // 第二步：写入 openclaw.json 配置
  // ============================================================

  console.log('');
  console.log('📝 [Step 2] 注入智谱模型配置...');

  // 重新读取（以防 Step 1 期间有变化）
  const { config } = readConfig();

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

  // models provider
  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
  };

  // agents 默认配置
  if (!config.agents) config.agents = {};
  if (!config.agents.defaults) config.agents.defaults = {};

  // 默认聊天模型
  config.agents.defaults.model = {
    primary: "zai/glm-5"
  };

  // 白名单: 增量添加，不覆盖已有模型
  if (!config.agents.defaults.models) config.agents.defaults.models = {};
  config.agents.defaults.models["zai/glm-5"] = {};

  writeConfig(config, configPath);

  // 验证写入
  const verify = readConfig();
  const writtenModelId = verify.config.models?.providers?.zai?.models?.[0]?.id || '???';
  const writtenDefault = verify.config.agents?.defaults?.model?.primary || '???';

  console.log('✅ 配置已注入');
  console.log('  [验证] model ID:  ' + writtenModelId);
  console.log('  [验证] default:   ' + writtenDefault);
  console.log('  [验证] 模型数量:  ' + verify.config.models?.providers?.zai?.models?.length);

  console.log('');
}

module.exports = { run };
