#!/usr/bin/env node
/**
 * build-report.js — 生成 SELF-CHECK.md（实际自检报告）
 *
 * 报告里的用例输出不是手写的，是当场执行 selfcheck.js / selfcheck-dom.js 抓下来的原始 stdout，
 * 因此报告与代码永远同步：重跑本脚本即可刷新。
 *
 * 运行： node outputs/build-report.js
 */
'use strict';

const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const PC = require('./profit-core.js');

const ROOT = path.resolve(__dirname, '..');
const SPEC = JSON.parse(fs.readFileSync(path.join(ROOT, 'inputs', 'spec.json'), 'utf8'));

/* ---------- 执行两个自检脚本，抓原始输出 ---------- */
function run(script) {
  const started = Date.now();
  let out = '', code = 0;
  try {
    out = execFileSync(process.execPath, [path.join(__dirname, script)], {
      encoding: 'utf8',
      cwd: __dirname,
      stdio: ['ignore', 'pipe', 'pipe']
    });
  } catch (e) {
    out = (e.stdout || '') + (e.stderr || '');
    code = typeof e.status === 'number' ? e.status : 1;
  }
  return { out: out.trimEnd(), code: code, ms: Date.now() - started };
}

const core = run('selfcheck.js');
const dom = run('selfcheck-dom.js');

/* ---------- 从输出里解析用例统计 ---------- */
function parseStats(text) {
  const m = text.match(/用例：(\d+)\s+通过：(\d+)\s+失败：(\d+)/);
  return m ? { total: +m[1], pass: +m[2], fail: +m[3] } : { total: 0, pass: 0, fail: 0 };
}
const coreStats = parseStats(core.out);
const domStats = parseStats(dom.out);

/* ---------- 现场核对关键数字 ---------- */
const r = PC.compute(SPEC);
const o = r.orders;
const money = (n) => PC.formatMoney(n);
const raw = (n) => (n === null ? '待补' : Number(n).toFixed(2).replace('-', '−'));

const now = new Date();
const stamp = now.getFullYear() + '-' + String(now.getMonth() + 1).padStart(2, '0') + '-' +
  String(now.getDate()).padStart(2, '0') + ' ' + String(now.getHours()).padStart(2, '0') + ':' +
  String(now.getMinutes()).padStart(2, '0');

const L = [];
const w = (s) => L.push(s === undefined ? '' : s);

w('# 自检报告 · 退货后利润核算工具（W29）');
w();
w('> 生成方式：`node outputs/build-report.js`。下面所有用例输出均为脚本当场执行的原始 stdout，非手写。');
w('> 本报告不替代人工 GUI 验收；浏览器内的布局、手机端断点仍需人眼确认。');
w();
w('| 项目 | 值 |');
w('| --- | --- |');
w('| 生成时间 | ' + stamp + ' |');
w('| Node 版本 | ' + process.version + ' |');
w('| 引擎版本 | profit-core.js v' + PC.VERSION + ' |');
w('| 输入文件 | `inputs/spec.json`（只读，' + SPEC.orders.length + ' 单，' + SPEC.currency + '） |');
w('| 核算口径 | 同一会计期 / 平台费不退 / 广告按给定分摊额 / 回收价值计入本期 |');
w('| 引擎自检 | ' + coreStats.pass + ' / ' + coreStats.total + ' 通过，失败 ' + coreStats.fail + ' |');
w('| 页面脚本自检 | ' + domStats.pass + ' / ' + domStats.total + ' 通过，失败 ' + domStats.fail + ' |');
w();

w('## 一、结论');
w();
const allPass = coreStats.fail === 0 && domStats.fail === 0 && core.code === 0 && dom.code === 0;
w(allPass
  ? '**全部通过。** 逐单净利润 37.00 / −28.00 / 24.00，合计 33.00，逐单合计与汇总差额 0.00；缺失与 null 一律标「待补」且不计入汇总；销售额 300.00 未被当作利润。'
  : '**存在失败用例，请查看下方原始输出。**');
w();

w('## 二、逐单数字核对');
w();
w('口径公式：`净利润 = 销售额 − 退款 − 货成本 − 去程运费 − 平台费 − 广告分摊 − 退回运费 + 回收价值`');
w();
w('| 单号 | 销售额 | 退款 | 货成本 | 去程 | 平台费 | 广告 | 退回运费 | 回收 | 净利润 | 代入验算 |');
w('| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | --- |');
o.forEach((x) => {
  const c = x.calc;
  const expr = raw(c.gross) + ' − ' + raw(c.refund) + ' − ' + raw(c.goodsCost) + ' − ' + raw(c.outbound) +
    ' − ' + raw(c.platformFeeCharged) + ' − ' + raw(c.adCharged) + ' − ' + raw(c.returnShipping) +
    ' + ' + raw(c.recoveryCounted);
  w('| ' + x.id + ' | ' + raw(c.gross) + ' | ' + raw(c.refund) + ' | ' + raw(c.goodsCost) + ' | ' +
    raw(c.outbound) + ' | ' + raw(c.platformFeeCharged) + ' | ' + raw(c.adCharged) + ' | ' +
    raw(c.returnShipping) + ' | ' + raw(c.recoveryCounted) + ' | **' + raw(c.netProfit) + '** | ' + expr + ' |');
});
w('| **合计** | ' + raw(r.totals.gross) + ' | ' + raw(r.totals.refund) + ' | ' + raw(r.totals.goodsCost) + ' | ' +
  raw(r.totals.outbound) + ' | ' + raw(r.totals.platformFeeCharged) + ' | ' + raw(r.totals.adCharged) + ' | ' +
  raw(r.totals.returnShipping) + ' | ' + raw(r.totals.recovery) + ' | **' + raw(r.totals.netProfit) + '** | 37.00 − 28.00 + 24.00 = 33.00 |');
w();
w('核对要点：');
w();
w('- 37.00 − 28.00 + 24.00 = **33.00**，与 `reconcile.orderProfitSum`、`totals.netProfit` 三处一致，差额 ' + money(r.reconcile.diff) + '。');
w('- 销售额 300.00 与净利润 33.00 相差 ' + money(PC.round2(r.totals.gross - r.totals.netProfit)) +
  '，正好等于「退款 100.00 + 成本 197.00 − 回收 30.00」。这是「销售额不是利润」的算术证据。');
w('- 净利率 ' + (r.totals.netMargin * 100).toFixed(2) + '%，远小于 100%，说明成本与退款真实进入了计算。');
w('- 每单 10 行勾稽阶梯的末行金额 = 该单净利润，且累计余额可由上一行加减本行复算（见 `selfcheck.js` 第 3 节）。');
w();

w('## 三、假设敏感性实测');
w();
w('| 广告分摊方式 | O1 | O2 | O3 | 净利润合计 |');
w('| --- | ---: | ---: | ---: | ---: |');
['fixed', 'revenue', 'netRevenue'].forEach((m) => {
  const x = PC.compute(SPEC, { adMethod: m });
  w('| ' + PC.AD_METHODS[m].label + ' | ' + x.orders.map((y) => raw(y.calc.netProfit)).join(' | ') + ' | **' + raw(x.totals.netProfit) + '** |');
});
w();
w('广告分摊方式只改变归属，不改变合计——三行合计都是 33.00。');
w();
w('| 平台费假设 | 平台费计入 | 退回 | 净利润合计 |');
w('| --- | ---: | ---: | ---: |');
['none', 'prorata', 'fullOnFullRefund'].forEach((p) => {
  const x = PC.compute(SPEC, { platformFeeRefund: p });
  w('| ' + PC.PLATFORM_METHODS[p].label + ' | ' + raw(x.totals.platformFeeCharged) + ' | ' +
    raw(x.totals.platformFeeRefunded) + ' | **' + raw(x.totals.netProfit) + '** |');
});
w();
w('平台费能否要回，让净利润在 33.00 ~ 38.00 之间摆动，差额 5.00 全部来自 O2 整单退款的平台费与 O3 部分退款的按比例退费。');
w();

w('## 四、空值处理实测（待补 ≠ 0）');
w();
const demoSpec = {
  currency: SPEC.currency,
  orders: SPEC.orders.concat([
    { id: 'O4', gross: 60, goodsCost: null, outbound: 8, platformFee: 3, adAllocated: 10, refund: 0, returnShipping: 0, returnedGoodsRecovery: 0 },
    { id: 'O5', gross: 90, goodsCost: 45, outbound: 8, platformFee: 5, adAllocated: 10, refund: 90, returnedGoodsRecovery: 45 },
    { id: 'O6', gross: 50, goodsCost: 20, outbound: 6, platformFee: '', adAllocated: 5, refund: 0, returnShipping: 0, returnedGoodsRecovery: 0 }
  ])
};
const d = PC.compute(demoSpec);
w('| 单号 | 空值形态 | 判定 | 净利润 | 处理 |');
w('| --- | --- | --- | --- | --- |');
const shapeMap = { O4: '`null`', O5: '字段不存在', O6: '空字符串 `""`' };
d.pendingOrders.forEach((p) => {
  w('| ' + p.id + ' | ' + (shapeMap[p.id] || '—') + ' | 待补（' + p.issues.map((i) => i.fieldLabel).join('、') +
    '） | **待补** | 剔除出汇总，不按 0 计入 |');
});
w();
/* 反例：把 O4 缺失的货成本当 0 会算出多少假利润（现场算，不写死） */
const wrongSpec = {
  currency: SPEC.currency,
  orders: SPEC.orders.concat([
    { id: 'O4', gross: 60, goodsCost: 0, outbound: 8, platformFee: 3, adAllocated: 10,
      refund: 0, returnShipping: 0, returnedGoodsRecovery: 0 }
  ])
};
const wrongRes = PC.compute(wrongSpec);
const wrongO4 = wrongRes.orders[3].calc.netProfit;
const wrongTotal = wrongRes.totals.netProfit;

w('- 加入 3 张待补单后，可核算订单仍为 ' + d.totals.okCount + ' 单，汇总净利润仍为 **' + raw(d.totals.netProfit) +
  '**（待补单未污染总额），口径标记变为「部分口径」。');
w('- 反例（现场计算）：若把 O4 缺失的货成本当成 0，该单会显示 **' + raw(wrongO4) +
  '** 的"利润"，整体净利润被抬到 **' + raw(wrongTotal) + '** ——多出来的 ' + raw(PC.round2(wrongTotal - d.totals.netProfit)) +
  ' 从未发生。工具拒绝这样做，这正是本项设计的核心。');
w('- 显式写 `0` 的订单则正常参与计算（`selfcheck.js` 6.2 节），「零」与「未知」被区别对待。');
w();

w('## 五、引擎自检原始输出（`node outputs/selfcheck.js`）');
w();
w('退出码 ' + core.code + '，耗时 ' + core.ms + ' ms。');
w();
w('```text');
w(core.out);
w('```');
w();

w('## 六、页面脚本自检原始输出（`node outputs/selfcheck-dom.js`）');
w();
w('说明：本项用一个极简 DOM 桩在 Node 里执行 `index.html` 的内联脚本，验证渲染链路、id 引用、数字与假设联动。');
w('它不能验证布局与视觉效果，也不驱动真实浏览器。');
w();
w('退出码 ' + dom.code + '，耗时 ' + dom.ms + ' ms。');
w();
w('```text');
w(dom.out);
w('```');
w();

w('## 七、已发现并修复的问题');
w();
w('| # | 问题 | 影响 | 处理 |');
w('| --- | --- | --- | --- |');
w('| 1 | 勾稽阶梯的「净利润」末行把净利润又累加了一次，余额显示 74 而非 37 | 末行余额与金额不一致，无法逐行复核 | 合计行/小计行改为取结果值本身，不再累加；`selfcheck.js` 第 3 节固化为断言 |');
w('| 2 | 小计行（净收入）金额输出为 `null`，只有余额列有值 | 表格该行金额缺失 | 小计行 `amount` 与 `running` 同为小计值 |');
w('| 3 | 广告总预算把待补订单的分摊额也计入，再摊给可核算订单 | 待补单的广告被摊到别人头上，合计从 33.00 被压到 23.00 | 预算基数只取可核算订单；被剔除的金额写进警告 |');
w('| 4 | 广告预算为 0 时误报「等分回退」 | 空白警告干扰判断 | 仅在预算 > 0 且权重全 0 时才回退等分 |');
w('| 5 | 预算为 0 的提示语写成「未给出分摊额」 | 与显式填 0 的事实不符 | 文案改为「给定分摊额合计为 0」 |');
w('| 6 | 待补行的「广告分摊」列显示「待补」，易被误读成广告数据缺失 | 口径歧义 | CSV 备注补「未参与广告分摊」 |');
w('| 7 | 页面自检桩的 `classList` 实现挂在错误对象上，且未继承 HTML 初始 class | 测试假失败/假通过 | 修桩，并补「初始渲染不得触发致命错误提示」断言 |');
w();

w('## 八、已知限制');
w();
w('- 全部数据为合成练习数据，仅 3 单（演示另加 3 单），不构成任何真实经营结论。');
w('- 不连接电商后台、不读取真实订单，无登录与接口调用；金额口径假设已在页面「计算口径与假设」区列出。');
w('- 不处理跨期摊销（如广告费按月分摊、退货跨月入库），全部按「同一期」简化。');
w('- 不处理税费、支付通道费、优惠券分摊等科目。');
w('- 页面自检基于 DOM 桩，无法覆盖真实浏览器的 CSS 布局、触屏交互与字体渲染；这部分由人工 GUI 验收。');
w();

fs.writeFileSync(path.join(__dirname, 'SELF-CHECK.md'), L.join('\n') + '\n', 'utf8');

console.log('已生成 SELF-CHECK.md');
console.log('  引擎自检 ' + coreStats.pass + '/' + coreStats.total + '（退出码 ' + core.code + '）');
console.log('  页面自检 ' + domStats.pass + '/' + domStats.total + '（退出码 ' + dom.code + '）');
console.log('  关键数字 O1=' + raw(o[0].calc.netProfit) + ' O2=' + raw(o[1].calc.netProfit) +
  ' O3=' + raw(o[2].calc.netProfit) + ' 合计=' + raw(r.totals.netProfit));
if (!allPass) {
  console.error('警告：存在失败的用例，报告已如实记录。');
  process.exit(1);
}
