#!/usr/bin/env node
/**
 * verify-links：交付前固定校验（技术提案第六节）。
 * 1) release.json 三个下载入口 URL 必须在目标 HTML 逐字出现；
 * 2) --http 时对三 URL 发 HEAD 探活（2xx/3xx 视为可达）。
 * 用法：node scripts/verify-links.mjs [目标html路径，默认 dist/index.html] [--http]
 * 退出码：0 全过；1 有失败项或文件不可读。
 */
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';

const here = dirname(fileURLToPath(import.meta.url));
const args = process.argv.slice(2);
const http = args.includes('--http');
const target = args.find((a) => !a.startsWith('--')) ?? resolve(here, '../dist/index.html');

const release = JSON.parse(readFileSync(resolve(here, '../src/data/release.json'), 'utf8'));
const entries = [
  ['macUrl', release.macUrl],
  ['winUrl', release.winUrl],
  ['ghUrl', release.ghUrl],
];

let html;
try {
  html = readFileSync(target, 'utf8');
} catch {
  console.error(`FAIL 目标文件不可读：${target}`);
  process.exit(1);
}

const results = [];
for (const [key, url] of entries) {
  const inPage = html.includes(url);
  let alive = null;
  if (http) {
    try {
      const res = await fetch(url, { method: 'HEAD', redirect: 'follow' });
      alive = res.ok || (res.status >= 300 && res.status < 400);
    } catch {
      alive = false;
    }
  }
  results.push({ key, url, inPage, alive });
}

let fail = 0;
for (const r of results) {
  const parts = [r.inPage ? 'PASS 逐字存在' : 'FAIL 未逐字出现'];
  if (http) parts.push(r.alive ? 'PASS HTTP可达' : 'FAIL HTTP不可达');
  if (!r.inPage || (http && !r.alive)) fail++;
  console.log(`${r.key}  ${r.url}  ${parts.join(' | ')}`);
}
console.log(fail === 0 ? 'verify-links: 全部通过' : `verify-links: ${fail} 项失败`);
process.exit(fail === 0 ? 0 : 1);
