#!/usr/bin/env node
/**
 * One-shot local dev TLS for *.localhost (no sudo needed).
 *
 * Usage: pnpm setup:local-test
 */
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  ADMIN_HOST,
  H5_HOST,
  H5_PUBLIC_BASE,
  OPS_HOST,
  PLAZA_HOST,
  PLAZA_PUBLIC_BASE,
  publicUrl,
  USES_LOCALHOST,
} from './local-test-config.mjs';

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

if (!USES_LOCALHOST) {
  if (process.getuid?.() !== 0) {
    console.log('非 *.localhost 域名需要 root 配置 DNS，请执行：');
    console.log('  sudo pnpm setup:local-test');
    process.exit(1);
  }
  const dns = spawnSync('node', [path.join(root, 'scripts/setup-local-test-dns.mjs')], {
    stdio: 'inherit',
    env: process.env,
  });
  if (dns.status !== 0) process.exit(dns.status ?? 1);
}

const tls = spawnSync('node', [path.join(root, 'scripts/local-test-tls.mjs')], {
  stdio: 'inherit',
  env: process.env,
});
if (tls.status !== 0) process.exit(tls.status ?? 1);

console.log('');
console.log('本地开发环境已配置。启动：');
console.log('  pnpm dev');
console.log('  pnpm dev:local-proxy    # 若 dev 未自动拉起 HTTPS 代理');
console.log('');
console.log('访问：');
console.log(`  MindSpace H5   ${H5_PUBLIC_BASE}/?preview=mindspace`);
console.log(`  memind_adm     ${publicUrl(ADMIN_HOST)}`);
console.log(`  Plaza          ${PLAZA_PUBLIC_BASE}/plaza`);
console.log(`  Ops 审核后台   ${publicUrl(OPS_HOST)}/ops/`);
