// @bun
import {
  PROVIDER_REGISTRY,
  init_providerRegistry
} from "./chunk-smkp5pcr.js";
import"./chunk-qp2qdcda.js";

// src/services/api/setupWizard.ts
init_providerRegistry();
import { createInterface } from "readline";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { join } from "path";
import { homedir } from "os";
import { createHash } from "crypto";
var CONFIG_DIR = join(homedir(), ".jialing-code");
var CONFIG_FILE = join(CONFIG_DIR, "config.json");
function loadConfig() {
  try {
    if (!existsSync(CONFIG_FILE))
      return null;
    return JSON.parse(readFileSync(CONFIG_FILE, "utf-8"));
  } catch {
    return null;
  }
}
function saveConfig(config) {
  if (!existsSync(CONFIG_DIR))
    mkdirSync(CONFIG_DIR, { recursive: true });
  writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2));
}
function hasConfig() {
  return existsSync(CONFIG_FILE);
}
function createRL() {
  return createInterface({ input: process.stdin, output: process.stdout });
}
function ask(rl, question) {
  return new Promise((resolve) => rl.question(question, (answer) => resolve(answer.trim())));
}
async function selectMenu(rl, title, options) {
  console.log(`
  ${title}
`);
  for (let i = 0;i < options.length; i++) {
    console.log(`    ${i + 1}. ${options[i].label}`);
  }
  console.log();
  while (true) {
    const answer = await ask(rl, `  \u8BF7\u8F93\u5165\u7F16\u53F7 (1-${options.length}): `);
    const idx = parseInt(answer, 10) - 1;
    if (idx >= 0 && idx < options.length)
      return options[idx].value;
    console.log("  \u274C \u65E0\u6548\u9009\u62E9\uFF0C\u8BF7\u91CD\u65B0\u8F93\u5165");
  }
}
async function fetchModels(baseURL, apiKey) {
  try {
    const url = `${baseURL.replace(/\/+$/, "")}/models`;
    const headers = { "Content-Type": "application/json" };
    if (apiKey && apiKey !== "ollama" && apiKey !== "none") {
      headers["Authorization"] = `Bearer ${apiKey}`;
    }
    const response = await fetch(url, { headers, signal: AbortSignal.timeout(15000) });
    if (!response.ok)
      return [];
    const data = await response.json();
    const models = [];
    if (data?.data && Array.isArray(data.data)) {
      for (const m of data.data) {
        if (m.id)
          models.push(m.id);
      }
    }
    models.sort((a, b) => a.length - b.length || a.localeCompare(b));
    return models;
  } catch {
    return [];
  }
}
var LICENSE_HASHES = new Set([
  "2352f11c7b38404b2ab5a135b3c429199a5a0ff7c04349c9179b3f58265f6b3a"
]);
function verifyLicense(key) {
  const hash = createHash("sha256").update(key).digest("hex");
  return LICENSE_HASHES.has(hash);
}
async function runSetupWizard() {
  const rl = createRL();
  console.log();
  console.log("  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
  console.log("  \u2551       \u5609\u9675\u6C5F-code \u914D\u7F6E\u5F15\u5BFC               \u2551");
  console.log("  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
  const mode = await selectMenu(rl, "\u8BF7\u9009\u62E9\u4F7F\u7528\u65B9\u5F0F:", [
    { label: "\u4F7F\u7528\u9ED8\u8BA4\u670D\u52A1\u5668\uFF08\u9700\u5BC6\u94A5\uFF09", value: "default" },
    { label: "\u4F7F\u7528\u7B2C\u4E09\u65B9\u5927\u6A21\u578B\u5382\u5546", value: "provider" },
    { label: "\u81EA\u5B9A\u4E49 API \u5730\u5740", value: "custom" }
  ]);
  let config;
  if (mode === "default") {
    config = await setupDefault(rl);
  } else if (mode === "provider") {
    config = await setupProvider(rl);
  } else {
    config = await setupCustom(rl);
  }
  saveConfig(config);
  rl.close();
  console.log();
  console.log("  \u2705 \u914D\u7F6E\u5DF2\u4FDD\u5B58\uFF01");
  console.log(`  \uD83D\uDCC1 \u914D\u7F6E\u6587\u4EF6: ${CONFIG_FILE}`);
  console.log(`  \uD83E\uDD16 \u6A21\u578B: ${config.model}`);
  console.log(`  \uD83D\uDD17 \u5730\u5740: ${config.baseURL}`);
  console.log();
  console.log("  \u8FD0\u884C jl --setup \u53EF\u91CD\u65B0\u914D\u7F6E");
  console.log();
  return config;
}
async function setupDefault(rl) {
  console.log();
  while (true) {
    const key = await ask(rl, "  \u8BF7\u8F93\u5165\u5BC6\u94A5: ");
    if (!key) {
      console.log("  \u274C \u5BC6\u94A5\u4E0D\u80FD\u4E3A\u7A7A");
      continue;
    }
    if (!verifyLicense(key)) {
      console.log("  \u274C \u5BC6\u94A5\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5");
      continue;
    }
    console.log("  \u2705 \u5BC6\u94A5\u9A8C\u8BC1\u901A\u8FC7");
    const baseURL = PROVIDER_REGISTRY.ollama.baseURL;
    console.log(`
  \u6B63\u5728\u83B7\u53D6\u53EF\u7528\u6A21\u578B\u5217\u8868...`);
    const models = await fetchModels(baseURL, "");
    let model;
    if (models.length > 0) {
      const options = models.map((m) => ({ label: m, value: m }));
      model = await selectMenu(rl, "\u8BF7\u9009\u62E9\u6A21\u578B:", options);
    } else {
      console.log("  \u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6A21\u578B\u5217\u8868\uFF0C\u8BF7\u624B\u52A8\u8F93\u5165");
      model = await ask(rl, "  \u6A21\u578B\u540D\u79F0 (\u9ED8\u8BA4 qwen3.5:35b): ") || "qwen3.5:35b";
    }
    return { provider: "ollama", baseURL, apiKey: "", model, licenseKey: key };
  }
}
async function setupProvider(rl) {
  const providerGroups = [
    { title: "\u2500\u2500 \u56FD\u9645\u5382\u5546 \u2500\u2500", ids: ["openai", "google", "mistral", "groq", "xai", "together", "cohere", "perplexity"] },
    { title: "\u2500\u2500 \u56FD\u5185\u5382\u5546 \u2500\u2500", ids: ["deepseek", "qwen", "zhipu", "moonshot", "doubao", "baidu", "yi", "stepfun", "baichuan", "minimax", "spark", "hunyuan"] },
    { title: "\u2500\u2500 \u805A\u5408\u5E73\u53F0 \u2500\u2500", ids: ["siliconflow", "openrouter", "ollama"] }
  ];
  const options = [];
  for (const group of providerGroups) {
    for (const id of group.ids) {
      const p = PROVIDER_REGISTRY[id];
      if (p)
        options.push({ label: `${p.name}`, value: id });
    }
  }
  const providerId = await selectMenu(rl, "\u8BF7\u9009\u62E9\u5382\u5546:", options);
  const provider = PROVIDER_REGISTRY[providerId];
  let apiKey = "";
  if (providerId !== "ollama") {
    const keyHint = provider.apiKeyEnvVars[0] || "API_KEY";
    apiKey = await ask(rl, `
  \u8BF7\u8F93\u5165 ${provider.name} API Key: `);
    if (!apiKey) {
      console.log("  \u26A0\uFE0F \u672A\u8F93\u5165 Key\uFF0C\u540E\u7EED\u9700\u901A\u8FC7\u73AF\u5883\u53D8\u91CF\u8BBE\u7F6E");
    }
  }
  const baseURL = provider.baseURL;
  console.log(`
  \u6B63\u5728\u83B7\u53D6\u53EF\u7528\u6A21\u578B\u5217\u8868...`);
  const models = await fetchModels(baseURL, apiKey);
  let model;
  if (models.length > 0) {
    const seen = new Set;
    const allOptions = [];
    for (const m of provider.models) {
      if (!seen.has(m.id)) {
        seen.add(m.id);
        const fetched = models.includes(m.id) ? " \u2713" : " (\u63A8\u8350)";
        allOptions.push({ label: `${m.id} \u2014 ${m.description}${fetched}`, value: m.id });
      }
    }
    for (const m of models) {
      if (!seen.has(m)) {
        seen.add(m);
        allOptions.push({ label: m, value: m });
      }
    }
    if (allOptions.length > 30) {
      const truncated = allOptions.slice(0, 30);
      truncated.push({ label: "\u624B\u52A8\u8F93\u5165\u5176\u4ED6\u6A21\u578B...", value: "__manual__" });
      model = await selectMenu(rl, `${provider.name} \u53EF\u7528\u6A21\u578B (\u5171${allOptions.length}\u4E2A):`, truncated);
    } else {
      model = await selectMenu(rl, `${provider.name} \u53EF\u7528\u6A21\u578B:`, allOptions);
    }
    if (model === "__manual__") {
      model = await ask(rl, `
  \u8BF7\u8F93\u5165\u6A21\u578B\u540D\u79F0: `) || provider.defaultModel;
    }
  } else {
    if (provider.models.length > 0) {
      const options2 = provider.models.map((m) => ({ label: `${m.id} \u2014 ${m.description}`, value: m.id }));
      options2.push({ label: "\u624B\u52A8\u8F93\u5165...", value: "__manual__" });
      model = await selectMenu(rl, `${provider.name} \u63A8\u8350\u6A21\u578B:`, options2);
      if (model === "__manual__") {
        model = await ask(rl, `
  \u8BF7\u8F93\u5165\u6A21\u578B\u540D\u79F0: `) || provider.defaultModel;
      }
    } else {
      model = await ask(rl, `
  \u8BF7\u8F93\u5165\u6A21\u578B\u540D\u79F0 (\u9ED8\u8BA4 ${provider.defaultModel}): `) || provider.defaultModel;
    }
  }
  return { provider: providerId, baseURL, apiKey, model };
}
async function setupCustom(rl) {
  const baseURL = await ask(rl, `
  \u8BF7\u8F93\u5165 API \u5730\u5740 (\u5982 http://localhost:11434/v1): `);
  if (!baseURL) {
    console.log("  \u274C \u5730\u5740\u4E0D\u80FD\u4E3A\u7A7A");
    return setupCustom(rl);
  }
  const apiKey = await ask(rl, "  \u8BF7\u8F93\u5165 API Key (\u65E0\u9700\u5219\u76F4\u63A5\u56DE\u8F66): ") || "";
  console.log(`
  \u6B63\u5728\u83B7\u53D6\u53EF\u7528\u6A21\u578B\u5217\u8868...`);
  const models = await fetchModels(baseURL, apiKey);
  let model;
  if (models.length > 0) {
    const options = models.slice(0, 30).map((m) => ({ label: m, value: m }));
    options.push({ label: "\u624B\u52A8\u8F93\u5165...", value: "__manual__" });
    model = await selectMenu(rl, "\u53EF\u7528\u6A21\u578B:", options);
    if (model === "__manual__") {
      model = await ask(rl, `
  \u8BF7\u8F93\u5165\u6A21\u578B\u540D\u79F0: `);
    }
  } else {
    console.log("  \u26A0\uFE0F \u65E0\u6CD5\u83B7\u53D6\u6A21\u578B\u5217\u8868");
    model = await ask(rl, "  \u8BF7\u8F93\u5165\u6A21\u578B\u540D\u79F0: ");
  }
  if (!model) {
    console.log("  \u274C \u6A21\u578B\u4E0D\u80FD\u4E3A\u7A7A");
    return setupCustom(rl);
  }
  return { provider: "custom", baseURL, apiKey, model };
}
function applyConfig(config) {
  if (config.provider === "ollama" && config.licenseKey) {
    process.env.JIALING_LICENSE_KEY = config.licenseKey;
  }
  if (config.apiKey) {
    process.env.OPENAI_API_KEY = config.apiKey;
  }
  if (config.baseURL) {
    process.env.OPENAI_BASE_URL = config.baseURL;
  }
  if (config.model) {
    process.env.OPENAI_MODEL = config.model;
  }
  if (config.provider && config.provider !== "custom") {
    process.env.PROVIDER = config.provider;
  }
  const providerCfg = PROVIDER_REGISTRY[config.provider];
  if (providerCfg && config.apiKey) {
    for (const envVar of providerCfg.apiKeyEnvVars) {
      process.env[envVar] = config.apiKey;
    }
  }
}
export {
  saveConfig,
  runSetupWizard,
  loadConfig,
  hasConfig,
  applyConfig
};
