#!/usr/bin/env node
/**
 * Add plaza.tkmind.cn ingress to cloudflared config (before catch-all 404).
 *
 * Usage:
 *   node scripts/patch-plaza-tunnel-config.mjs
 *   CLOUDFLARE_TUNNEL_CONFIG=/path/to/config.yml PLAZA_TUNNEL_PORT=3001 node ...
 */
import fs from 'node:fs';

const configPath =
  process.env.CLOUDFLARE_TUNNEL_CONFIG ??
  '/Users/john/Project/ollama/cloudflare/config.yml';
const plazaPort = Number(process.env.PLAZA_TUNNEL_PORT ?? process.env.PLAZA_PORT ?? 3001);
const plazaHost = process.env.PLAZA_LOCAL_HOST ?? 'plaza.tkmind.cn';

if (!fs.existsSync(configPath)) {
  console.error(`错误: 未找到 cloudflared 配置：${configPath}`);
  console.error('请设置 CLOUDFLARE_TUNNEL_CONFIG');
  process.exit(1);
}

let content = fs.readFileSync(configPath, 'utf8');

if (content.includes(`hostname: ${plazaHost}`)) {
  const current = content.match(
    new RegExp(`hostname: ${plazaHost.replace('.', '\\.')}[\\s\\S]*?service: (http://[^\\n]+)`),
  );
  const target = `http://127.0.0.1:${plazaPort}`;
  if (current?.[1] === target) {
    console.log(`cloudflared 已配置 ${plazaHost} → ${target}`);
    process.exit(0);
  }
  content = content.replace(
    new RegExp(
      `(hostname: ${plazaHost.replace('.', '\\.')}[\\s\\S]*?service: )http://127\\.0\\.0\\.1:\\d+`,
    ),
    `$1${target}`,
  );
  fs.writeFileSync(configPath, content);
  console.log(`已更新 ${plazaHost} → ${target}`);
  process.exit(0);
}

const block = `  - hostname: ${plazaHost}
    service: http://127.0.0.1:${plazaPort}
    originRequest:
      connectTimeout: 30s
      keepAliveTimeout: 90s
      disableChunkedEncoding: false
`;

if (!content.includes('- service: http_status:404')) {
  console.error('错误: 配置中未找到 catch-all http_status:404 规则');
  process.exit(1);
}

content = content.replace(/\n  - service: http_status:404/, `\n${block}\n  - service: http_status:404`);
fs.writeFileSync(configPath, content);
console.log(`已添加 ${plazaHost} → http://127.0.0.1:${plazaPort}`);
