import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createDbPool } from '../db.mjs';
import { createLlmProviderService, testRelayConnection } from '../llm-providers.mjs';

const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');

function loadEnvFile(filePath) {
  if (!fs.existsSync(filePath)) return;
  for (const line of fs.readFileSync(filePath, 'utf8').split('\n')) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith('#')) continue;
    const eq = trimmed.indexOf('=');
    if (eq < 0) continue;
    const key = trimmed.slice(0, eq).trim();
    const value = trimmed.slice(eq + 1).trim();
    if (!process.env[key]) process.env[key] = value;
  }
}

loadEnvFile(path.join(root, '.env'));
loadEnvFile(path.join(root, '../tkmind_go/.env.local'));

const relayToken = process.env.CUSTOM_RELAY_BUYER_DEEPSEEK_API_KEY?.trim();
if (!relayToken) {
  console.error('缺少 CUSTOM_RELAY_BUYER_DEEPSEEK_API_KEY（tkmind_go/.env.local）');
  process.exit(1);
}

const pool = createDbPool();
const svc = createLlmProviderService(pool, {
  apiTarget: process.env.TKMIND_API_TARGET ?? 'https://127.0.0.1:18006',
  apiSecret: process.env.TKMIND_SERVER__SECRET_KEY ?? 'local-dev-secret',
});

const [rows] = await pool.query(
  'SELECT id FROM h5_llm_provider_keys WHERE is_selected = 1 LIMIT 1',
);
const id = rows[0]?.id;
if (!id) {
  console.error('未找到已启用的 LLM 配置');
  process.exit(1);
}

const updated = await svc.updateKey(id, {
  name: 'TKMind Relay DeepSeek',
  apiUrl: 'https://andu.tkmind.cn/relay/buyer/v1/chat/completions',
  apiKey: relayToken,
  models: ['deepseek-chat', 'deepseek-reasoner'],
  defaultModel: 'deepseek-chat',
  relayProvider: 'deepseek',
});

if (!updated.ok) {
  console.error('更新失败:', updated.message);
  process.exit(1);
}

await svc.syncSelectedToGoosed();
const test = await testRelayConnection({
  apiUrl: 'https://andu.tkmind.cn/relay/buyer/v1/chat/completions',
  apiKey: relayToken,
  model: 'deepseek-chat',
  relayProvider: 'deepseek',
});

console.log('LLM 配置已更新为 andu DeepSeek relay');
console.log('连通测试:', test.ok ? `OK (${test.latencyMs}ms)` : test.message);
await pool.end();
