#!/usr/bin/env node
/* ================================================================
   构建脚本：把 parser-core.js + app.js + styles.css + 示例数据
   内联进单个 index.html，保证 file:// 双击即可离线使用。
   用法：node scripts/build.js
   ================================================================ */
'use strict';

const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const ROOT = path.resolve(__dirname, '..');            // outputs/
const PROJECT = path.resolve(ROOT, '..');               // D49/
const TEMPLATE = path.join(ROOT, 'src', 'index.template.html');
const CORE = path.join(ROOT, 'parser-core.js');
const APP = path.join(ROOT, 'src', 'app.js');
const CSS = path.join(ROOT, 'src', 'styles.css');
const SPEC = path.join(PROJECT, 'inputs', 'spec.json');
const TARGET = path.join(ROOT, 'index.html');

function read(file) {
  return fs.readFileSync(file, 'utf8');
}

function replaceOnce(html, token, content, label) {
  const count = html.split(token).length - 1;
  if (count !== 1) {
    throw new Error('模板占位符 ' + label + ' 出现 ' + count + ' 次，期望 1 次');
  }
  return html.split(token).join(content);
}

function escapeForInlineJson(json) {
  return json
    .replace(/</g, '\\u003c')
    .replace(/>/g, '\\u003e')
    .replace(/&/g, '\\u0026')
    .replace(/\u2028/g, '\\u2028')
    .replace(/\u2029/g, '\\u2029');
}

function main() {
  const template = read(TEMPLATE);
  const core = read(CORE);
  const app = read(APP);
  const css = read(CSS);
  const spec = JSON.parse(read(SPEC));

  if (!spec || !Array.isArray(spec.logs)) {
    throw new Error('inputs/spec.json 缺少 logs 数组');
  }

  [['styles.css', css], ['parser-core.js', core], ['app.js', app]].forEach(([name, text]) => {
    if (/<\/script/i.test(text)) {
      throw new Error(name + ' 含有 </script，无法安全内联');
    }
  });
  if (/<\/style/i.test(css)) {
    throw new Error('styles.css 含有 </style，无法安全内联');
  }

  const sampleJson = JSON.stringify(spec, null, 2);

  let html = template;
  html = replaceOnce(html, '/*__INLINE_CSS__*/', css, 'INLINE_CSS');
  html = replaceOnce(html, '<!--__SAMPLE_JSON__-->', escapeForInlineJson(sampleJson), 'SAMPLE_JSON');
  html = replaceOnce(html, '/*__INLINE_CORE__*/', core, 'INLINE_CORE');
  html = replaceOnce(html, '/*__INLINE_APP__*/', app, 'INLINE_APP');

  if (html.indexOf('__INLINE_') !== -1 || html.indexOf('__SAMPLE_JSON__') !== -1) {
    throw new Error('仍有未替换的模板占位符');
  }

  fs.writeFileSync(TARGET, html, 'utf8');

  const bytes = Buffer.byteLength(html, 'utf8');
  const sha = crypto.createHash('sha256').update(html, 'utf8').digest('hex');
  console.log('已生成 ' + path.relative(PROJECT, TARGET));
  console.log('  大小：' + (bytes / 1024).toFixed(1) + ' KiB（' + bytes + ' 字节）');
  console.log('  SHA-256：' + sha);
  console.log('  示例行数：' + spec.logs.length);
  console.log('  外部依赖：无（样式/脚本/示例数据均已内联）');
}

try {
  main();
} catch (err) {
  console.error('构建失败：' + err.message);
  process.exit(1);
}