#!/usr/bin/env node
/**
 * Open plaza.tkmind.cn in a browser with local host mapping.
 * Chromium Secure DNS bypasses /etc/hosts — host-resolver-rules fixes that.
 *
 * Usage: node scripts/open-plaza-local.mjs
 */
import { spawnSync } from 'node:child_process';

const host = process.env.PLAZA_LOCAL_HOST ?? 'plaza.tkmind.cn';
const url = (process.env.PLAZA_PUBLIC_BASE ?? `https://${host}`).replace(/\/$/, '') + '/plaza';
const rules = `MAP ${host} 127.0.0.1`;

const attempts = [
  {
    label: 'Google Chrome',
    cmd: 'open',
    args: ['-na', 'Google Chrome', '--args', `--host-resolver-rules=${rules}`, url],
  },
  {
    label: 'Microsoft Edge',
    cmd: 'open',
    args: ['-na', 'Microsoft Edge', '--args', `--host-resolver-rules=${rules}`, url],
  },
  {
    label: 'Safari',
    cmd: 'open',
    args: ['-a', 'Safari', url],
  },
];

for (const attempt of attempts) {
  const result = spawnSync(attempt.cmd, attempt.args, { stdio: 'ignore' });
  if (result.status === 0) {
    console.log(`已在 ${attempt.label} 打开：${url}`);
    if (attempt.label !== 'Safari') {
      console.log('（已通过 --host-resolver-rules 强制解析到 127.0.0.1）');
    }
    console.log('若提示证书不受信任，选择「继续访问」即可。');
    process.exit(0);
  }
}

console.log('未找到 Chrome/Edge/Safari。请手动：');
console.log(`  1. 关闭浏览器「安全 DNS / Secure DNS」`);
console.log(`  2. 打开 ${url}`);
console.log(`  3. 或访问 http://127.0.0.1:3001/plaza`);
