/*!
 * build.js — 生成二维码资产、可打印卡片与独立单文件网页。
 * 运行：node tools/build.js （工作目录为 outputs/）
 *
 * 依赖：qrcode（MIT）
 * 生成物全部写入 outputs/ 下的 qr/、cards/、print-cards.html、index.standalone.html。
 */
'use strict';

const fs = require('fs');
const path = require('path');
const QRCode = require('qrcode');

const ROOT = path.resolve(__dirname, '..');
const CORE = require(path.join(ROOT, 'hunt-core.js'));

const opts = { errorCorrectionLevel: 'M', margin: 4 };
const QUIET = 4;

function ensure(dir) {
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}

function esc(s) {
  return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

async function buildQr(clue) {
  const code = clue.code;
  const svg = await QRCode.toString(code, Object.assign({}, opts, { type: 'svg' }));
  const png = await QRCode.toBuffer(code, Object.assign({}, opts, { type: 'png', width: 600 }));
  const qr = QRCode.create(code, { errorCorrectionLevel: 'M' });
  return { svg, png, modules: qr.modules.size, version: qr.version };
}

// 把官方 SVG 字符串的 inner 内容抽出（<path …/> 等），便于嵌入卡片。
function extractInnerSvg(svgStr) {
  return svgStr
    .replace(/^<svg[^>]*>/, '')
    .replace(/<\/svg>\s*$/, '')
    .trim();
}

// 每关一种强调色（赛博霓虹，兼顾打印清晰度）。
const ACCENTS = ['#0ecfc8', '#2f7df6', '#b36ef5', '#f8779e', '#ffb02e', '#54d66a'];

// 生成单张卡片 SVG（二维码使用官方 toString 的 inner 内容，保证与 PNG 编码一致）。
function makeCardSvg(clue, index, officialSvg, moduleSize) {
  const accent = ACCENTS[index % ACCENTS.length];
  const W = 600, H = 760;
  const qrSize = 340;
  const qrX = (W - qrSize) / 2;
  const qrY = 296;
  const viewBoxN = moduleSize + QUIET * 2; // 模块数 + 两侧静区
  const inner = extractInnerSvg(String(officialSvg).trim());
  const no = index + 1;
  const totalN = CORE.TOTAL;
  return `<?xml version="1.0" encoding="UTF-8"?>
<svg width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" xmlns="http://www.w3.org/2000/svg" font-family="-apple-system,'PingFang SC','Microsoft YaHei',sans-serif">
  <defs>
    <linearGradient id="grad${index}" x1="0" y1="0" x2="1" y2="1">
      <stop offset="0" stop-color="${accent}"/>
      <stop offset="1" stop-color="#0a0f1e"/>
    </linearGradient>
  </defs>
  <rect x="0" y="0" width="${W}" height="${H}" rx="26" fill="#ffffff"/>
  <rect x="0" y="0" width="${W}" height="${H}" rx="26" fill="none" stroke="${accent}" stroke-width="5"/>
  <rect x="0" y="0" width="${W}" height="12" rx="6" fill="url(#grad${index})"/>
  <text x="${W / 2}" y="70" text-anchor="middle" font-size="26" font-weight="700" fill="#0a0f1e">赛博游园会 · 离线寻宝</text>
  <text x="${W / 2}" y="102" text-anchor="middle" font-size="17" fill="#5c6b87">— 六张卡的谜题挑战 · 第 ${no} 关 / 共 ${totalN} 关 —</text>
  <text x="${W / 2}" y="150" text-anchor="middle" font-size="42" font-weight="800" fill="${accent}">C${no}</text>
  <text x="${W / 2}" y="196" text-anchor="middle" font-size="22" font-weight="600" fill="#0a0f1e">谜题</text>
  <text x="${W / 2}" y="240" text-anchor="middle" font-size="30" font-weight="700" fill="#0a0f1e">${esc(clue.riddle)}</text>
  <rect x="${qrX - 16}" y="${qrY - 16}" width="${qrSize + 32}" height="${qrSize + 32}" rx="16" fill="#ffffff" stroke="${accent}" stroke-width="2.5"/>
  <svg x="${qrX}" y="${qrY}" width="${qrSize}" height="${qrSize}" viewBox="0 0 ${viewBoxN} ${viewBoxN}" shape-rendering="crispEdges" preserveAspectRatio="xMidYMid meet">${inner}</svg>
  <text x="${W / 2}" y="${qrY + qrSize + 52}" text-anchor="middle" font-size="20" font-family="ui-monospace,Menlo,Consolas,monospace" fill="#0a0f1e">${esc(clue.code)}</text>
  <text x="${W / 2}" y="${H - 42}" text-anchor="middle" font-size="18" fill="#5c6b87">扫描二维码 → 到校验页粘贴编号并作答</text>
  <text x="${W / 2}" y="${H - 16}" text-anchor="middle" font-size="14" fill="#9aa9c4">合成练习材料 · 不涉及真实奖品或收费</text>
</svg>`;
}

async function main() {
  ensure(path.join(ROOT, 'qr'));
  ensure(path.join(ROOT, 'cards'));

  const manifest = [];
  const cardSvgs = [];
  let standaloneCardHtml = '';

  for (let i = 0; i < CORE.CLUES.length; i++) {
    const clue = CORE.CLUES[i];
    const id = clue.id;
    const built = await buildQr(clue);

    // 1) 独立二维码 SVG / PNG
    fs.writeFileSync(path.join(ROOT, 'qr', `${id}.svg`), built.svg + '\n');
    fs.writeFileSync(path.join(ROOT, 'qr', `${id}.png`), built.png);

    // 2) 单张卡片 SVG（使用官方 SVG inner，保证与 PNG 一致）
    const cardSvg = makeCardSvg(clue, i, built.svg, built.modules);
    fs.writeFileSync(path.join(ROOT, 'cards', `card-${id}.svg`), cardSvg + '\n');
    cardSvgs.push({ id, svg: cardSvg });

    // 3) 供 print-cards.html 使用的内联版本
    standaloneCardHtml += `<section class="card">\n${cardSvg}\n</section>\n`;

    manifest.push({
      id,
      code: clue.code,
      riddle: clue.riddle,
      answer: clue.answer,
      next: clue.next,
      qr: { version: built.version, modules: built.modules + QUIET * 2, errorCorrectionLevel: opts.errorCorrectionLevel, margin: opts.margin }
    });
    console.log(`[build] ${id} -> ${clue.code} (version ${built.version}, ${built.modules}×${built.modules} + quiet zone)`);
  }

  fs.writeFileSync(path.join(ROOT, 'qr', 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n');

  // 4) print-cards.html（6 张卡片，中英文说明，打印友好）
  const printHtml = `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>赛博游园会 · 可打印谜题卡（共 6 张）</title>
<style>
  :root{--cyan:#0ecfc8;--ink:#0a0f1e;--muted:#5c6b87}
  *{box-sizing:border-box}
  body{margin:0;padding:16px;background:#eef1f7;color:var(--ink);
    font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}
  h1{font-size:22px;margin:4px 0 2px}
  .tip{color:var(--muted);font-size:13px;margin:0 0 14px}
  .grid{display:grid;grid-template-columns:1fr;gap:16px;max-width:960px;margin:0 auto}
  .card{break-inside:avoid;page-break-inside:avoid;background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 4px 18px rgba(10,15,30,.12)}
  .card svg{display:block;width:100%;height:auto}
  @media(min-width:560px){.grid{grid-template-columns:1fr 1fr}}
  @media print{
    body{background:#fff;padding:0}
    h1,.tip{display:none}
    .grid{grid-template-columns:1fr 1fr;gap:0;max-width:none}
    .card{box-shadow:none;border-radius:0;page-break-inside:avoid;break-inside:avoid}
  }
  @page{size:A4;margin:8mm}
</style>
</head>
<body>
  <h1>赛博游园会 · 离线寻宝（可打印谜题卡）</h1>
  <p class="tip">共 ${CORE.TOTAL} 张卡片。可直接打印或保存为 PDF，沿卡片边缘裁开。扫描任意一张上的二维码得到编号，粘贴到校验页（index.html）作答。二维码内容为固定编号（如 CYBERFETE-HUNT:C1），不是文件链接。</p>
  <div class="grid">
${standaloneCardHtml}  </div>
</body>
</html>
`;
  fs.writeFileSync(path.join(ROOT, 'print-cards.html'), printHtml);

  // 5) index.standalone.html（把 hunt-core.js 内联进 index.html，单文件离线可用）
  const indexHtml = fs.readFileSync(path.join(ROOT, 'index.html'), 'utf8');
  const coreSrc = fs.readFileSync(path.join(ROOT, 'hunt-core.js'), 'utf8');
  const standalone = indexHtml.replace('<script src="hunt-core.js"></script>', '<script>\n' + coreSrc + '\n</script>');
  fs.writeFileSync(path.join(ROOT, 'index.standalone.html'), standalone);

  console.log('[build] 完成。qr/*.svg, qr/*.png, qr/manifest.json, cards/card-*.svg, print-cards.html, index.standalone.html');
}

main().catch(function (e) {
  console.error('[build] 失败：', e);
  process.exit(1);
});