#!/usr/bin/env node
import fs from 'node:fs';
import http from 'node:http';
import https from 'node:https';
import {
  ADMIN_HOST,
  allHostsConfigured,
  H5_HOST,
  H5_PUBLIC_BASE,
  OPS_HOST,
  PLAZA_HOST,
  PLAZA_PUBLIC_BASE,
  PUBLIC_PORT,
  USES_LOCALHOST,
  publicUrl,
} from './local-test-config.mjs';

function checkUrl(url) {
  const parsed = new URL(url);
  const transport = parsed.protocol === 'https:' ? https : http;
  return new Promise((resolve) => {
    const req = transport.request(
      {
        hostname: parsed.hostname,
        port: parsed.port || (parsed.protocol === 'https:' ? 443 : 80),
        path: `${parsed.pathname}${parsed.search}`,
        method: 'GET',
        rejectUnauthorized: false,
        headers: parsed.hostname === PLAZA_HOST ? { Host: `${PLAZA_HOST}:${process.env.PLAZA_PORT ?? 3001}` } : {},
      },
      (res) => resolve(res.statusCode ?? 0),
    );
    req.on('error', () => resolve(0));
    req.setTimeout(3000, () => {
      req.destroy();
      resolve(0);
    });
    req.end();
  });
}

console.log('==> 本地开发环境诊断');
console.log(`    模式：${USES_LOCALHOST ? '*.localhost (:8443)' : 'custom tkmind.cn domains'}`);
console.log('');

const issues = [];

if (!USES_LOCALHOST && !allHostsConfigured()) {
  issues.push('DNS 未配置 → sudo pnpm setup:local-test');
} else if (USES_LOCALHOST) {
  console.log('✓ *.localhost 无需 /etc/hosts');
} else {
  for (const host of [H5_HOST, ADMIN_HOST, PLAZA_HOST, OPS_HOST]) {
    console.log(`✓ DNS  ${host}`);
  }
}

const tlsDir = new URL('../.local/local-test-tls/', import.meta.url);
if (!fs.existsSync(new URL('./local-test.cert.pem', tlsDir))) {
  issues.push('TLS 证书缺失 → pnpm setup:local-test');
} else {
  console.log('✓ TLS  证书已生成');
}

console.log('');
console.log(`==> HTTPS 入口 (:${PUBLIC_PORT}，pnpm dev:local-proxy)`);

const checks = [
  ['H5', `${H5_PUBLIC_BASE}/`, 200],
  ['memind_adm', `${publicUrl(ADMIN_HOST)}/healthz`, 200],
  ['Plaza', `${PLAZA_PUBLIC_BASE}/plaza`, 200],
  ['Ops', `${publicUrl(OPS_HOST)}/ops/`, 200],
];

for (const [label, url, expected] of checks) {
  const code = await checkUrl(url);
  if (code === expected || (label === 'Plaza' && [200, 307, 308].includes(code))) {
    console.log(`✓ ${label.padEnd(12)} ${url}  → ${code}`);
  } else {
    console.log(`✗ ${label.padEnd(12)} ${url}  → ${code || '不可达'}`);
    if (code === 0) {
      issues.push(`${label} 不可达：pnpm dev && pnpm dev:local-proxy`);
    }
  }
}

console.log('');
if (issues.length) {
  console.log('待处理：');
  for (const issue of issues) console.log(`  - ${issue}`);
  process.exit(1);
}

console.log('本地开发环境正常。');
console.log(`打开 H5：pnpm open:local-test`);
