#!/usr/bin/env node
/**
 * ResearchPad Agent - AccessKey 写入脚本
 * 
 * 接收 AccessKey，验证格式，写入 Roo settings.json（Roo openai provider + OpenAI-compatible endpoint）
 * 并持久化到 ~/.researchpad-agent/access-key.json
 * 
 * 使用方式:
 *   node set-access-key.js <ACCESS_KEY>
 *   或被 proxy-httpproxy.js 的 /api/set-access-key 路由调用
 */
'use strict';

const fs = require('fs');
const os = require('os');
const path = require('path');

const HOME = os.homedir();
const AGENT_DIR = path.join(HOME, '.researchpad-agent');
const ACCESS_KEY_FILE = path.join(AGENT_DIR, 'access-key.json');

// Roo settings paths
const WEB_DIR = path.join(HOME, '.researchpad-agent-web');
const USER_DATA_DIR = path.join(WEB_DIR, 'User');
const SETTINGS_PATH = path.join(USER_DATA_DIR, 'settings.json');
const LEGACY_SETTINGS_PATH = path.join(USER_DATA_DIR, 'User', 'settings.json');
const ROO_IMPORT_FILE = path.join(WEB_DIR, 'roo-code-settings.json');

// ResearchPad 代理服务器配置
const RESEARCHPAD_PROXY_URL = 'https://api.co-scientist.cc';
const DEEPSEEK_MODEL = 'deepseek-v3.2';
const PROFILE_NAME = 'ResearchPad DeepSeek (AccessKey)';
const PROFILE_ID = 'researchpad-accesskey';
const ROO_BUILTIN_MODES = ['architect', 'code', 'ask', 'debug', 'orchestrator'];

function buildModeApiConfigs() {
  return Object.fromEntries(ROO_BUILTIN_MODES.map((mode) => [mode, PROFILE_ID]));
}

function readJson(file, fallback = {}) {
  if (!fs.existsSync(file)) return fallback;
  try {
    return JSON.parse(fs.readFileSync(file, 'utf8'));
  } catch {
    return fallback;
  }
}

function writeJson(file, value) {
  fs.mkdirSync(path.dirname(file), { recursive: true });
  fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`);
}

/**
 * 验证 AccessKey 格式（23位）
 */
function validateAccessKey(key) {
  if (!key || typeof key !== 'string') return false;
  return key.trim().length === 23;
}

/**
 * 读取当前存储的 AccessKey
 */
function getStoredAccessKey() {
  const data = readJson(ACCESS_KEY_FILE, null);
  return data?.accessKey || '';
}

/**
 * 保存 AccessKey 到本地持久化文件
 */
function saveAccessKey(accessKey) {
  writeJson(ACCESS_KEY_FILE, {
    accessKey,
    updatedAt: new Date().toISOString(),
    proxyUrl: RESEARCHPAD_PROXY_URL,
    model: DEEPSEEK_MODEL,
  });
}

/**
 * 将 AccessKey 写入 Roo/ResearchPad 的 settings.json
 * 使用 Roo 的 openai provider，通过 OpenAI-compatible 本地代理中转到 api.co-scientist.cc
 */
function updateRooSettings(accessKey) {
  // 更新 Roo import settings (provider profiles)
  const rooImport = {
    providerProfiles: {
      currentApiConfigName: PROFILE_NAME,
      apiConfigs: {
        [PROFILE_NAME]: {
          id: PROFILE_ID,
          apiProvider: 'openai',
          openAiModelId: DEEPSEEK_MODEL,
          // 指向本地代理的 /api/chat/completions 端点
          // 本地代理负责 OpenAI -> Gemini 格式转换 -> api.co-scientist.cc
          openAiBaseUrl: 'https://local.researchpad.org:8443/api/v1',
          openAiApiKey: accessKey,
        },
      },
      modeApiConfigs: buildModeApiConfigs(),
    },
    globalSettings: {
      telemetrySetting: 'disabled',
    },
  };

  writeJson(ROO_IMPORT_FILE, rooImport);

  // 更新 VS Code settings.json。code-server 的真实路径是 User/settings.json；
  // 旧版本曾写入 User/User/settings.json，这里同步两份避免运行态读到旧配置。
  for (const settingsPath of [SETTINGS_PATH, LEGACY_SETTINGS_PATH]) {
    const settings = readJson(settingsPath);
    settings['roo-cline.apiProvider'] = 'openai';
    settings['roo-cline.openAiBaseUrl'] = 'https://local.researchpad.org:8443/api/v1';
    settings['roo-cline.openAiApiKey'] = accessKey;
    settings['roo-cline.openAiModelId'] = DEEPSEEK_MODEL;
    settings['roo-cline.autoImportSettingsPath'] = ROO_IMPORT_FILE;

    // 清除旧的 DeepSeek 直连配置
    delete settings['roo-cline.deepSeekApiKey'];
    delete settings['roo-cline.deepSeekBaseUrl'];
    delete settings['roo-cline.deepSeekModelId'];

    writeJson(settingsPath, settings);
  }
}

/**
 * 主函数：设置 AccessKey
 * @returns {{ success: boolean, message: string }}
 */
function setAccessKey(accessKey) {
  if (!validateAccessKey(accessKey)) {
    return { success: false, message: 'Invalid AccessKey format (must be 23 characters)' };
  }

  const trimmedKey = accessKey.trim();

  try {
    // 1. 持久化到本地
    saveAccessKey(trimmedKey);

    // 2. 写入 Roo settings
    updateRooSettings(trimmedKey);

    console.log(`[set-access-key] ✅ AccessKey 已设置 (${trimmedKey.substring(0, 6)}...)`);
    return { success: true, message: 'AccessKey set successfully' };
  } catch (error) {
    console.error(`[set-access-key] ❌ 设置失败:`, error.message);
    return { success: false, message: error.message };
  }
}

// CLI 入口
if (require.main === module) {
  const key = process.argv[2];
  if (!key) {
    console.error('Usage: node set-access-key.js <ACCESS_KEY>');
    process.exit(1);
  }
  const result = setAccessKey(key);
  if (!result.success) {
    console.error(result.message);
    process.exit(1);
  }
}

module.exports = { setAccessKey, getStoredAccessKey, validateAccessKey };
