#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""W04 补货建议生成脚本（可重复运行）。

读取 ../inputs/库存.csv（只读），按 ../inputs/规则.md 口径计算补货建议，
生成三件套到本目录（outputs/）：
  - 补货建议.csv
  - 补货建议.xlsx
  - 补货看板.html

口径（规则.md）：
  日均 = 近7天销量 / 7
  可售天数 = 库存 / 日均（日均=0 时不适用）
  目标 = 日均 * (交货期天 + 安全天数)
  净需求 = max(0, 目标 - 库存 - 在途)
  整箱建议 = ceil(净需求 / 箱规) * 箱规；停销商品不建议采购，强制为 0
  预计缺货风险 = 库存 / 日均 < 交货期天（严格小于；等于交货期不算提前缺货）
  停销与零销量为独立状态：停销不采购；零销量单列待人工判断。

运行：/Users/macmini_no1/.cache/codex-runtimes/codex-primary-runtime/dependencies/python/bin/python3 generate.py
"""
from __future__ import annotations

import csv
import html
import json
import math
import subprocess
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
INPUT_CSV = BASE.parent / "inputs" / "库存.csv"

OUT_CSV = BASE / "补货建议.csv"
OUT_XLSX = BASE / "补货建议.xlsx"
OUT_HTML = BASE / "补货看板.html"

AIGC_LABEL = "AI-generated"
AIGC_XATTR = "aigc"
AIGC_META = json.dumps(
    {
        "label": AIGC_LABEL,
        "generator": "WorkBuddy W04 generate.py",
        "note": "合成数据，不可据此下单",
    },
    ensure_ascii=False,
)


# ---------------------------------------------------------------- helpers
def fmt_num(v: float | int | None) -> str:
    """整数不带小数点，其余保留两位小数。"""
    if v is None:
        return "不适用"
    if isinstance(v, str):
        return v
    if abs(float(v) - round(float(v))) < 1e-9:
        return str(int(round(float(v))))
    return f"{float(v):.2f}"


def fmt_days(v: float | None) -> str:
    if v is None:
        return "不适用"
    return f"{v:.2f}"


def mark_ai_generated(path: Path) -> None:
    """用文件属性（扩展属性）标识 AI 生成；失败不阻塞产物写出。"""
    try:
        subprocess.run(
            ["xattr", "-w", AIGC_XATTR, AIGC_META, str(path)],
            check=True,
            capture_output=True,
        )
    except Exception as exc:  # pragma: no cover - 平台差异兜底
        print(f"[warn] 设置文件属性失败 {path.name}: {exc}", file=sys.stderr)


# ---------------------------------------------------------------- core calc
def load_rows() -> list[dict]:
    with INPUT_CSV.open("r", encoding="utf-8-sig", newline="") as f:
        reader = csv.DictReader(f)
        rows = []
        for r in reader:
            if not r.get("SKU"):
                continue
            rows.append(
                {
                    "SKU": r["SKU"].strip(),
                    "名称": r["名称"].strip(),
                    "库存": float(r["库存"]),
                    "在途": float(r["在途"]),
                    "近7天销量": float(r["近7天销量"]),
                    "交货期天": float(r["交货期天"]),
                    "安全天数": float(r["安全天数"]),
                    "箱规": float(r["箱规"]),
                    "源状态": r["状态"].strip(),
                }
            )
    return rows


def compute(row: dict) -> dict:
    sales7 = row["近7天销量"]
    stock = row["库存"]
    inflight = row["在途"]
    lead = row["交货期天"]
    safety = row["安全天数"]
    case_pack = row["箱规"]
    stopped = row["源状态"] == "停销"
    zero_sales = sales7 == 0

    daily = sales7 / 7.0
    # 可售天数 = 库存/日均；日均=0 时不适用
    sellable_days = None if daily == 0 else stock / daily
    target = daily * (lead + safety)
    net_demand = max(0.0, target - stock - inflight)

    # 整箱建议 = ceil(净需求/箱规)*箱规；停销不建议采购 → 0
    if stopped or net_demand <= 0 or case_pack <= 0:
        suggest = 0
    else:
        suggest = int(math.ceil(net_demand / case_pack) * case_pack)

    # 预计缺货风险 = 库存/日均 < 交货期（严格小于）；日均=0 不适用
    if daily == 0:
        risk_flag = "不适用"
        risk_bool = None
    else:
        risk_bool = (stock / daily) < lead
        risk_flag = "是" if risk_bool else "否"

    # 分类（独立状态）：停销 > 零销量 > 需要补货 > 库存充足
    if stopped:
        category = "停销"
    elif zero_sales:
        category = "零销量"
    elif suggest > 0:
        category = "需要补货"
    else:
        category = "库存充足"

    # 筛选分组
    if category == "需要补货":
        group = "replenish"
    elif category in ("停销", "零销量"):
        group = "manual"
    else:
        group = "normal"

    # 计算链（可解释展示）
    chain_parts = [
        f"日均={fmt_num(sales7)}÷7={daily:.2f}",
        f"目标={daily:.2f}×({fmt_num(lead)}+{fmt_num(safety)})={target:.2f}",
        f"净需求=max(0,{target:.2f}-{fmt_num(stock)}-{fmt_num(inflight)})={fmt_num(net_demand)}",
    ]
    if stopped:
        chain_parts.append("停销不建议采购→整箱建议=0")
    else:
        chain_parts.append(
            f"整箱建议=ceil({fmt_num(net_demand)}÷{fmt_num(case_pack)})×{fmt_num(case_pack)}={suggest}"
        )

    # 风险依据
    if stopped:
        reason = (
            f"停销商品不建议采购，整箱建议强制为0（净需求{fmt_num(net_demand)}仅作参考）；"
            f"可售{fmt_days(sellable_days)}天<交货期{fmt_num(lead)}天"
            if sellable_days is not None and risk_bool
            else f"停销商品不建议采购，整箱建议强制为0（净需求{fmt_num(net_demand)}仅作参考）"
        )
    elif zero_sales:
        reason = "零销量：日均=0，可售天数与需求无法预估，单列待人工判断（是否继续备货或清退）"
    else:
        risk_txt = (
            f"可售{fmt_days(sellable_days)}天<交货期{fmt_num(lead)}天，存在提前缺货风险"
            if risk_bool
            else f"可售{fmt_days(sellable_days)}天≥交货期{fmt_num(lead)}天，无提前缺货风险"
        )
        cover = stock + inflight
        cover_txt = (
            f"库存+在途{fmt_num(cover)}≥目标{fmt_num(target)}，无需补货"
            if net_demand <= 0
            else f"净需求{fmt_num(net_demand)}，整箱向上取整为{suggest}"
        )
        reason = f"{risk_txt}；{cover_txt}"

    return {
        **row,
        "日均": daily,
        "可售天数": sellable_days,
        "目标": target,
        "净需求": net_demand,
        "整箱建议": suggest,
        "预计缺货风险": risk_flag,
        "分类": category,
        "group": group,
        "风险依据": reason,
        "计算链": "；".join(chain_parts),
    }


# ---------------------------------------------------------------- self test
def self_test(rows: list[dict]) -> None:
    """生成前按夹具校验计算口径，防止公式回归。"""
    by = {r["SKU"]: r for r in rows}
    expect = {
        # SKU: (日均, 可售天数|None, 目标, 净需求, 整箱建议, 风险, 分类)
        "A": (10.0, 1.0, 30.0, 20.0, 24, "是", "需要补货"),
        "B": (5.0, 10.0, 25.0, 0.0, 0, "否", "库存充足"),
        "C": (0.0, None, 0.0, 0.0, 0, "不适用", "零销量"),
        "D": (10.0, 0.0, 30.0, 30.0, 0, "是", "停销"),
        "E": (3.0, 2.0 / 3.0, 9.0, 4.0, 6, "是", "需要补货"),
        "F": (2.0, 0.0, 4.0, 4.0, 5, "是", "需要补货"),
    }
    for sku, (d, dd, t, n, s, risk, cat) in expect.items():
        r = by[sku]
        assert abs(r["日均"] - d) < 1e-9, f"{sku} 日均 {r['日均']} != {d}"
        if dd is None:
            assert r["可售天数"] is None, f"{sku} 可售天数应为不适用"
        else:
            assert abs(r["可售天数"] - dd) < 1e-9, f"{sku} 可售天数 {r['可售天数']} != {dd}"
        assert abs(r["目标"] - t) < 1e-9, f"{sku} 目标 {r['目标']} != {t}"
        assert abs(r["净需求"] - n) < 1e-9, f"{sku} 净需求 {r['净需求']} != {n}"
        assert r["整箱建议"] == s, f"{sku} 整箱建议 {r['整箱建议']} != {s}"
        assert r["预计缺货风险"] == risk, f"{sku} 风险 {r['预计缺货风险']} != {risk}"
        assert r["分类"] == cat, f"{sku} 分类 {r['分类']} != {cat}"
    # 合计校验
    assert sum(r["净需求"] for r in rows) == 58.0
    assert sum(r["整箱建议"] for r in rows) == 35
    print("[self-test] 6 行夹具断言全部通过")


# ---------------------------------------------------------------- writers
CSV_COLUMNS = [
    "SKU", "名称", "状态", "分类", "库存", "在途", "近7天销量", "交货期天", "安全天数", "箱规",
    "日均", "可售天数", "目标", "净需求", "整箱建议", "预计缺货风险", "风险依据", "计算链",
]


def write_csv(rows: list[dict]) -> None:
    with OUT_CSV.open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.writer(f)
        w.writerow(CSV_COLUMNS)
        for r in rows:
            w.writerow(
                [
                    r["SKU"], r["名称"], r["源状态"], r["分类"],
                    fmt_num(r["库存"]), fmt_num(r["在途"]), fmt_num(r["近7天销量"]),
                    fmt_num(r["交货期天"]), fmt_num(r["安全天数"]), fmt_num(r["箱规"]),
                    f"{r['日均']:.2f}", fmt_days(r["可售天数"]),
                    f"{r['目标']:.2f}", fmt_num(r["净需求"]), r["整箱建议"],
                    r["预计缺货风险"], r["风险依据"], r["计算链"],
                ]
            )
    mark_ai_generated(OUT_CSV)


def write_xlsx(rows: list[dict]) -> None:
    from openpyxl import Workbook
    from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
    from openpyxl.utils import get_column_letter

    wb = Workbook()
    wb.properties.creator = "WorkBuddy AI"
    wb.properties.title = "补货建议"
    wb.properties.description = f"{AIGC_LABEL} · 合成数据，不可据此下单"
    wb.properties.keywords = "AI-generated"

    ws = wb.active
    ws.title = "补货建议"
    ws.append(CSV_COLUMNS)
    for r in rows:
        ws.append(
            [
                r["SKU"], r["名称"], r["源状态"], r["分类"],
                r["库存"], r["在途"], r["近7天销量"], r["交货期天"], r["安全天数"], r["箱规"],
                round(r["日均"], 2), (round(r["可售天数"], 2) if r["可售天数"] is not None else "不适用"),
                round(r["目标"], 2), r["净需求"], r["整箱建议"],
                r["预计缺货风险"], r["风险依据"], r["计算链"],
            ]
        )

    header_fill = PatternFill("solid", fgColor="D9E2F3")
    thin = Side(style="thin", color="BFBFBF")
    border = Border(left=thin, right=thin, top=thin, bottom=thin)
    for cell in ws[1]:
        cell.font = Font(bold=True)
        cell.fill = header_fill
        cell.alignment = Alignment(vertical="center", wrap_text=True)
        cell.border = border
    widths = [8, 10, 8, 12, 8, 8, 12, 10, 10, 8, 8, 10, 8, 8, 10, 12, 46, 60]
    for i, width in enumerate(widths, start=1):
        ws.column_dimensions[get_column_letter(i)].width = width
    for row in ws.iter_rows(min_row=2):
        for cell in row:
            cell.border = border
            cell.alignment = Alignment(vertical="top", wrap_text=cell.column >= 17)
    ws.freeze_panes = "A2"

    # 口径说明页（可解释）
    ws2 = wb.create_sheet("口径说明")
    ws2.append(["项目", "口径"])
    rules = [
        ("日均", "近7天销量 ÷ 7"),
        ("可售天数", "库存 ÷ 日均；日均=0 时为「不适用」"),
        ("目标", "日均 ×（交货期天 + 安全天数）"),
        ("净需求", "max(0, 目标 − 库存 − 在途)"),
        ("整箱建议", "ceil(净需求 ÷ 箱规) × 箱规；停销商品不建议采购，强制为 0"),
        ("预计缺货风险", "库存 ÷ 日均 < 交货期天（严格小于；等于交货期不算提前缺货）"),
        ("停销", "独立状态：不建议采购，整箱建议=0"),
        ("零销量", "独立状态：日均=0，单列待人工判断"),
        ("数据声明", "所有数据为合成数据，不可据此下单"),
    ]
    for item in rules:
        ws2.append(list(item))
    ws2.column_dimensions["A"].width = 16
    ws2.column_dimensions["B"].width = 72
    for cell in ws2[1]:
        cell.font = Font(bold=True)
        cell.fill = header_fill
    wb.save(OUT_XLSX)
    mark_ai_generated(OUT_XLSX)


def write_html(rows: list[dict]) -> None:
    rows_json = json.dumps(
        [
            {
                "sku": r["SKU"],
                "name": r["名称"],
                "srcStatus": r["源状态"],
                "category": r["分类"],
                "group": r["group"],
                "stock": r["库存"],
                "inflight": r["在途"],
                "sales7": r["近7天销量"],
                "lead": r["交货期天"],
                "safety": r["安全天数"],
                "casePack": r["箱规"],
                "daily": r["日均"],
                "sellable": r["可售天数"],
                "target": r["目标"],
                "netDemand": r["净需求"],
                "suggest": r["整箱建议"],
                "riskFlag": r["预计缺货风险"],
                "reason": r["风险依据"],
                "chain": r["计算链"],
            }
            for r in rows
        ],
        ensure_ascii=False,
    )
    n_all = len(rows)
    n_rep = sum(1 for r in rows if r["group"] == "replenish")
    n_man = sum(1 for r in rows if r["group"] == "manual")

    page = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="WorkBuddy W04 generate.py">
<meta name="aigc" content="{AIGC_LABEL}">
<title>补货看板</title>
<style>
  :root {{
    --bg: #f5f6f8; --card: #ffffff; --text: #1f2329; --muted: #646a73;
    --line: #e4e7ed; --accent: #245bdb; --accent-bg: #eaf1ff;
    --red: #c2251c; --red-bg: #ffece8; --green: #1a7f37; --green-bg: #e9f7ef;
    --amber: #b26200; --amber-bg: #fff4e0; --gray: #6b7280; --gray-bg: #eef0f3;
  }}
  * {{ box-sizing: border-box; }}
  body {{ margin: 0; padding: 24px; background: var(--bg); color: var(--text);
         font: 14px/1.6 "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; }}
  .wrap {{ max-width: 1280px; margin: 0 auto; }}
  header h1 {{ margin: 0 0 4px; font-size: 22px; }}
  header p {{ margin: 0; color: var(--muted); }}
  .banner {{ margin: 14px 0 18px; padding: 10px 14px; background: var(--amber-bg);
             border: 1px solid #f0d19b; border-radius: 8px; color: var(--amber); }}
  .card {{ background: var(--card); border: 1px solid var(--line); border-radius: 10px;
           padding: 16px 18px; margin-bottom: 16px; }}
  .card h2 {{ margin: 0 0 10px; font-size: 15px; }}
  .formula {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 8px 18px; }}
  .formula div {{ color: var(--muted); }}
  .formula b {{ color: var(--text); font-weight: 600; }}
  .filters {{ display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }}
  .filters button {{ padding: 7px 16px; border-radius: 999px; border: 1px solid var(--line);
    background: var(--card); color: var(--text); cursor: pointer; font-size: 13px; }}
  .filters button:hover {{ border-color: var(--accent); color: var(--accent); }}
  .filters button.active {{ background: var(--accent); border-color: var(--accent); color: #fff; }}
  .kpis {{ display: flex; flex-wrap: wrap; gap: 12px; margin: 14px 0 0; }}
  .kpi {{ flex: 1 1 160px; background: var(--accent-bg); border-radius: 8px; padding: 10px 14px; }}
  .kpi .label {{ color: var(--muted); font-size: 12px; }}
  .kpi .value {{ font-size: 22px; font-weight: 700; margin-top: 2px; }}
  .table-wrap {{ overflow-x: auto; }}
  table {{ border-collapse: collapse; width: 100%; min-width: 1100px; }}
  th, td {{ border-bottom: 1px solid var(--line); padding: 8px 10px; text-align: left;
            vertical-align: top; white-space: nowrap; }}
  td.wrap-cell {{ white-space: normal; min-width: 220px; }}
  th {{ background: #f0f3f8; font-size: 12px; color: var(--muted); position: sticky; top: 0; }}
  tr:hover td {{ background: #fafbfd; }}
  tfoot td {{ font-weight: 700; background: #f0f3f8; border-top: 2px solid var(--line); }}
  .tag {{ display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: 12px; }}
  .tag-ok {{ background: var(--green-bg); color: var(--green); }}
  .tag-need {{ background: var(--red-bg); color: var(--red); }}
  .tag-stop {{ background: var(--gray-bg); color: var(--gray); }}
  .tag-zero {{ background: var(--amber-bg); color: var(--amber); }}
  .risk-yes {{ color: var(--red); font-weight: 600; }}
  .risk-no {{ color: var(--green); }}
  .risk-na {{ color: var(--muted); }}
  .chain {{ color: var(--muted); font-size: 12px; }}
  footer {{ color: var(--muted); font-size: 12px; margin: 18px 0 8px; }}
  .num {{ text-align: right; font-variant-numeric: tabular-nums; }}
</style>
</head>
<body>
<div class="wrap">
  <header>
    <h1>补货看板</h1>
    <p>近 7 天销量口径 · 目标 = 日均 ×（交货期 + 安全天数）· 整箱建议向上取整 · 停销 / 零销量独立状态</p>
  </header>

  <div class="banner">⚠️ 所有数据为合成数据，仅供展示与验收，<b>不可据此下单</b>。本页面不含任何下单功能。</div>

  <section class="card">
    <h2>口径说明（可解释）</h2>
    <div class="formula">
      <div><b>日均</b> = 近7天销量 ÷ 7</div>
      <div><b>可售天数</b> = 库存 ÷ 日均（日均=0 → 不适用）</div>
      <div><b>目标</b> = 日均 ×（交货期天 + 安全天数）</div>
      <div><b>净需求</b> = max(0, 目标 − 库存 − 在途)</div>
      <div><b>整箱建议</b> = ceil(净需求 ÷ 箱规) × 箱规；<b>停销不建议采购 → 0</b></div>
      <div><b>预计缺货风险</b> = 库存 ÷ 日均 &lt; 交货期天（严格小于；等于交货期不算提前缺货）</div>
      <div><b>停销</b>：独立状态，不建议采购</div>
      <div><b>零销量</b>：独立状态，单列待人工判断</div>
    </div>
  </section>

  <section class="card">
    <h2>筛选与合计</h2>
    <div class="filters" role="group" aria-label="筛选">
      <button type="button" data-group="all" class="active">全部（{n_all}）</button>
      <button type="button" data-group="replenish">需要补货（{n_rep}）</button>
      <button type="button" data-group="manual">需人工判断（{n_man}）</button>
    </div>
    <div class="kpis">
      <div class="kpi"><div class="label">当前 SKU 数</div><div class="value" id="kpi-count">0</div></div>
      <div class="kpi"><div class="label">净需求合计</div><div class="value" id="kpi-net">0</div></div>
      <div class="kpi"><div class="label">整箱建议合计</div><div class="value" id="kpi-suggest">0</div></div>
    </div>
    <p class="chain" style="margin:10px 0 0">合计随上方筛选实时更新；「需人工判断」= 停销 + 零销量。</p>
  </section>

  <section class="card">
    <h2>补货明细</h2>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>SKU</th><th>名称</th><th>状态</th><th>分类</th>
            <th class="num">库存</th><th class="num">在途</th><th class="num">近7天销量</th>
            <th class="num">日均</th><th class="num">可售天数</th>
            <th class="num">目标</th><th class="num">净需求</th><th class="num">整箱建议</th>
            <th>预计缺货风险</th><th>风险依据</th><th>计算链</th>
          </tr>
        </thead>
        <tbody id="tbody"></tbody>
        <tfoot>
          <tr>
            <td colspan="4">合计（随筛选）</td>
            <td class="num" id="t-stock"></td>
            <td class="num" id="t-inflight"></td>
            <td class="num" id="t-sales"></td>
            <td class="num">—</td><td class="num">—</td><td class="num">—</td>
            <td class="num" id="t-net"></td>
            <td class="num" id="t-suggest"></td>
            <td colspan="3">—</td>
          </tr>
        </tfoot>
      </table>
    </div>
  </section>

  <footer>
    状态图例：<span class="tag tag-need">需要补货</span>
    <span class="tag tag-ok">库存充足</span>
    <span class="tag tag-stop">停销</span>
    <span class="tag tag-zero">零销量</span>
    　·　本页面由 AI 生成（aigc），数据来源 inputs/库存.csv 与 inputs/规则.md。
  </footer>
</div>

<script>
const ROWS = {rows_json};
const TAG_CLASS = {{
  "需要补货": "tag-need",
  "库存充足": "tag-ok",
  "停销": "tag-stop",
  "零销量": "tag-zero",
}};

function fmtNum(v) {{
  if (v === null || v === undefined) return "不适用";
  if (Math.abs(v - Math.round(v)) < 1e-9) return String(Math.round(v));
  return v.toFixed(2);
}}
function fmtDays(v) {{
  return (v === null || v === undefined) ? "不适用" : v.toFixed(2);
}}

function riskCell(flag) {{
  if (flag === "是") return '<span class="risk-yes">是</span>';
  if (flag === "否") return '<span class="risk-no">否</span>';
  return '<span class="risk-na">不适用</span>';
}}

function render(group) {{
  const rows = group === "all" ? ROWS : ROWS.filter(r => r.group === group);
  const tbody = document.getElementById("tbody");
  tbody.innerHTML = rows.map(r => `
    <tr>
      <td>${{r.sku}}</td>
      <td>${{r.name}}</td>
      <td>${{r.srcStatus}}</td>
      <td><span class="tag ${{TAG_CLASS[r.category] || ''}}">${{r.category}}</span></td>
      <td class="num">${{fmtNum(r.stock)}}</td>
      <td class="num">${{fmtNum(r.inflight)}}</td>
      <td class="num">${{fmtNum(r.sales7)}}</td>
      <td class="num">${{r.daily.toFixed(2)}}</td>
      <td class="num">${{fmtDays(r.sellable)}}</td>
      <td class="num">${{r.target.toFixed(2)}}</td>
      <td class="num">${{fmtNum(r.netDemand)}}</td>
      <td class="num"><b>${{r.suggest}}</b></td>
      <td>${{riskCell(r.riskFlag)}}</td>
      <td class="wrap-cell">${{r.reason}}</td>
      <td class="wrap-cell chain">${{r.chain}}</td>
    </tr>`).join("");

  const sumNet = rows.reduce((s, r) => s + r.netDemand, 0);
  const sumSug = rows.reduce((s, r) => s + r.suggest, 0);
  const sumStock = rows.reduce((s, r) => s + r.stock, 0);
  const sumIn = rows.reduce((s, r) => s + r.inflight, 0);
  const sumSales = rows.reduce((s, r) => s + r.sales7, 0);

  document.getElementById("kpi-count").textContent = rows.length;
  document.getElementById("kpi-net").textContent = fmtNum(sumNet);
  document.getElementById("kpi-suggest").textContent = sumSug;
  document.getElementById("t-stock").textContent = fmtNum(sumStock);
  document.getElementById("t-inflight").textContent = fmtNum(sumIn);
  document.getElementById("t-sales").textContent = fmtNum(sumSales);
  document.getElementById("t-net").textContent = fmtNum(sumNet);
  document.getElementById("t-suggest").textContent = sumSug;
}}

document.querySelectorAll(".filters button").forEach(btn => {{
  btn.addEventListener("click", () => {{
    document.querySelectorAll(".filters button").forEach(b => b.classList.remove("active"));
    btn.classList.add("active");
    render(btn.dataset.group);
  }});
}});

render("all");
</script>
</body>
</html>
"""
    OUT_HTML.write_text(page, encoding="utf-8")
    mark_ai_generated(OUT_HTML)


# ---------------------------------------------------------------- main
def main() -> None:
    raw = load_rows()
    rows = [compute(r) for r in raw]
    self_test(rows)
    write_csv(rows)
    write_xlsx(rows)
    write_html(rows)
    print(f"[done] 生成 {OUT_CSV.name} / {OUT_XLSX.name} / {OUT_HTML.name}（{len(rows)} 行）")


if __name__ == "__main__":
    main()
