# -*- coding: utf-8 -*-
"""
赛博游园会 第二批 W02 采购差额归因 —— 可重复运行生成脚本

输入（只读）:
    ../inputs/上月.csv
    ../inputs/本月.csv
    ../inputs/口径.md

口径:
    同品: 数量影响 = (本月量 - 上月量) * 上月价
          价格影响 = 本月量 * (本月价 - 上月价)
    新品: 本月全额列新品影响（上月无该 SKU）
    停采: 负上月全额列停采影响（本月无该 SKU）
    不把交叉项计算两次；按 SKU 匹配。

输出（写入本脚本所在目录）:
    采购归因.csv     纯数字明细
    采购归因.xlsx    Excel 明细 + 校验
    采购分析.html    离线 CSS 条形图 + 全部/同品/新增/停采筛选
    核算说明.md      核算过程说明
    README.md        交付物说明

用法:
    /Users/macmini_no1/.cache/codex-runtimes/codex-primary-runtime/dependencies/python/bin/python3 generate.py
"""
import csv
import json
import os

BASE = os.path.dirname(os.path.abspath(__file__))
INPUT_DIR = os.path.join(BASE, "..", "inputs")
OUT = BASE  # 成品均写入 outputs（脚本随成品放于同目录）

# ---------- 1. 读取原始输入 ----------
def read_inputs():
    def read(fn):
        rows = []
        with open(os.path.join(INPUT_DIR, fn), "r", encoding="utf-8-sig") as f:
            for r in csv.DictReader(f):
                rows.append({
                    "sku": r["SKU"].strip(),
                    "name": r["名称"].strip(),
                    "qty": float(r["数量"]),
                    "price": float(r["单价"]),
                })
        return {r["sku"]: r for r in rows}

    return read("上月.csv"), read("本月.csv")

# ---------- 2. 归因计算 ----------
def compute(prev, curr):
    items = []
    for sku in sorted(set(prev) | set(curr)):
        p, c = prev.get(sku), curr.get(sku)
        name = (c or p)["name"]
        qty_imp = price_imp = new_imp = stop_imp = 0.0
        if p and c:  # 同品
            qty_imp = (c["qty"] - p["qty"]) * p["price"]
            price_imp = c["qty"] * (c["price"] - p["price"])
        elif c and not p:  # 新品: 本月全额
            new_imp = c["qty"] * c["price"]
        elif p and not c:  # 停采: 负上月全额
            stop_imp = -(p["qty"] * p["price"])
        items.append({
            "sku": sku, "name": name,
            "prev_qty": p["qty"] if p else 0.0,
            "prev_price": p["price"] if p else 0.0,
            "prev_amt": (p["qty"] * p["price"]) if p else 0.0,
            "curr_qty": c["qty"] if c else 0.0,
            "curr_price": c["price"] if c else 0.0,
            "curr_amt": (c["qty"] * c["price"]) if c else 0.0,
            "qty_imp": qty_imp, "price_imp": price_imp,
            "new_imp": new_imp, "stop_imp": stop_imp,
            "type": "同品" if (p and c) else ("新增" if c else "停采"),
        })
    total_imp = sum(i["qty_imp"] + i["price_imp"] + i["new_imp"] + i["stop_imp"] for i in items)
    diff = sum(i["curr_amt"] for i in items) - sum(i["prev_amt"] for i in items)
    assert abs(total_imp - diff) < 1e-9, f"校验失败: 影响 {total_imp} != 差额 {diff}"
    return items, diff

# ---------- 3. 采购归因.csv（纯数字明细） ----------
def write_csv(items, prev_total, curr_total, diff):
    path = os.path.join(OUT, "采购归因.csv")
    with open(path, "w", encoding="utf-8-sig", newline="") as f:
        w = csv.writer(f)
        w.writerow(["SKU", "名称", "类别",
                    "上月数量", "上月单价", "上月金额",
                    "本月数量", "本月单价", "本月金额",
                    "数量影响", "价格影响", "新品影响", "停采影响", "影响合计"])
        for i in items:
            imp_sum = i["qty_imp"] + i["price_imp"] + i["new_imp"] + i["stop_imp"]
            w.writerow([i["sku"], i["name"], i["type"],
                        fmt(i["prev_qty"]), fmt(i["prev_price"]), fmt(i["prev_amt"]),
                        fmt(i["curr_qty"]), fmt(i["curr_price"]), fmt(i["curr_amt"]),
                        fmt(i["qty_imp"]), fmt(i["price_imp"]),
                        fmt(i["new_imp"]), fmt(i["stop_imp"]), fmt(imp_sum)])
        w.writerow(["合计", "", "", "", "", fmt(prev_total),
                    "", "", fmt(curr_total),
                    fmt(sum(i["qty_imp"] for i in items)),
                    fmt(sum(i["price_imp"] for i in items)),
                    fmt(sum(i["new_imp"] for i in items)),
                    fmt(sum(i["stop_imp"] for i in items)), fmt(diff)])
    print("写出:", path)

def fmt(x):
    return f"{x:g}"

# ---------- 4. 采购归因.xlsx ----------
def write_xlsx(items, prev_total, curr_total, diff):
    from openpyxl import Workbook
    from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
    from openpyxl.utils import get_column_letter

    wb = Workbook()
    ws = wb.active
    ws.title = "采购归因"

    headers = ["SKU", "名称", "类别", "上月数量", "上月单价", "上月金额",
               "本月数量", "本月单价", "本月金额",
               "数量影响", "价格影响", "新品影响", "停采影响", "影响合计"]
    ws.append(headers)
    hfill = PatternFill("solid", fgColor="1F4E79")
    hfont = Font(color="FFFFFF", bold=True)
    thin = Border(*[Side(style="thin", color="CCCCCC")] * 4)
    for c in ws[1]:
        c.fill, c.font, c.alignment, c.border = hfill, hfont, Alignment("center", "center"), thin

    def row_cells(i, bold=False):
        imp_sum = i["qty_imp"] + i["price_imp"] + i["new_imp"] + i["stop_imp"]
        vals = [i["sku"], i["name"], i["type"],
                i["prev_qty"], i["prev_price"], i["prev_amt"],
                i["curr_qty"], i["curr_price"], i["curr_amt"],
                i["qty_imp"], i["price_imp"], i["new_imp"], i["stop_imp"], imp_sum]
        ws.append(vals)
        r = ws.max_row
        fill = None
        if i["type"] == "新增":
            fill = PatternFill("solid", fgColor="E2EFDA")
        elif i["type"] == "停采":
            fill = PatternFill("solid", fgColor="FCE4EC")
        for c in ws[r]:
            c.border = thin
            if fill:
                c.fill = fill
            if bold:
                c.font = Font(bold=True)
            if c.column >= 4:
                c.number_format = "0.00;-0.00;\"—\""

    for i in items:
        row_cells(i)
    # 合计行
    ws.append(["合计", "", "", "", "", prev_total, "", "", curr_total,
               sum(i["qty_imp"] for i in items), sum(i["price_imp"] for i in items),
               sum(i["new_imp"] for i in items), sum(i["stop_imp"] for i in items), diff])
    for c in ws[ws.max_row]:
        c.font = Font(bold=True)
        c.border = thin
        c.fill = PatternFill("solid", fgColor="FFF2CC")
        if c.column >= 4:
            c.number_format = "0.00;-0.00;\"—\""

    # 校验行
    r = ws.max_row + 2
    ws.cell(r, 1, "校验").font = Font(bold=True)
    ws.cell(r, 2, f"本月总额 - 上月总额 = {curr_total:g} - {prev_total:g} = {diff:g}；"
                  f"数量+价格+新品+停采影响合计 = {diff:g}，两者一致 ✓")

    widths = [8, 10, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
    for idx, wd in enumerate(widths, 1):
        ws.column_dimensions[get_column_letter(idx)].width = wd
    ws.freeze_panes = "A2"

    path = os.path.join(OUT, "采购归因.xlsx")
    wb.save(path)
    print("写出:", path)

# ---------- 5. 采购分析.html ----------
def write_html(items, prev_total, curr_total, diff):
    def esc(s):
        return s.replace("&", "&amp;").replace("<", "&lt;")

    def n(x):
        v = f"{x:,.2f}"
        return v.rstrip("0").rstrip(".") if "." in v else v

    max_imp = max((abs(i["qty_imp"]) + abs(i["price_imp"]) + abs(i["new_imp"]) + abs(i["stop_imp"]))
                  for i in items) or 1.0

    rows_js = []
    rows_html = []
    for i in items:
        total = i["qty_imp"] + i["price_imp"] + i["new_imp"] + i["stop_imp"]
        rows_js.append({
            "sku": i["sku"], "name": i["name"], "type": i["type"],
            "pq": i["prev_qty"], "pp": i["prev_price"], "pa": i["prev_amt"],
            "cq": i["curr_qty"], "cp": i["curr_price"], "ca": i["curr_amt"],
            "qty": i["qty_imp"], "price": i["price_imp"],
            "new": i["new_imp"], "stop": i["stop_imp"], "total": total,
        })
        # 每类影响的条形段
        segs = ""
        for key, label, cls in (("qty_imp", "数量", "seg-qty"), ("price_imp", "价格", "seg-price"),
                                ("new_imp", "新品", "seg-new"), ("stop_imp", "停采", "seg-stop")):
            v = i[key]
            if abs(v) < 1e-9:
                continue
            w = abs(v) / max_imp * 100
            pos = v >= 0
            segs += (f'<div class="bar-row"><span class="bar-label">{label}</span>'
                     f'<div class="bar-track"><div class="bar {cls} {"bar-neg" if not pos else ""}" '
                     f'style="width:{w:.1f}%"></div></div>'
                     f'<span class="bar-val">{"+" if pos else ""}{n(v)}</span></div>')
        if not segs:
            segs = '<div class="bar-row"><span class="bar-label">—</span><div class="bar-track"></div><span class="bar-val">0</span></div>'
        tag = {"同品": "tag-same", "新增": "tag-new", "停采": "tag-stop"}[i["type"]]
        rows_html.append(f'''
<tr class="item" data-type="{i["type"]}">
  <td class="sku">{esc(i["sku"])}</td>
  <td>{esc(i["name"])} <span class="tag {tag}">{i["type"]}</span></td>
  <td class="num">{n(i["prev_qty"])}</td><td class="num">{n(i["prev_price"])}</td><td class="num">{n(i["prev_amt"])}</td>
  <td class="num">{n(i["curr_qty"])}</td><td class="num">{n(i["curr_price"])}</td><td class="num">{n(i["curr_amt"])}</td>
  <td class="num">—</td>
  <td class="chart">{segs}</td>
  <td class="num total-cell {"pos" if total > 0 else ("neg" if total < 0 else "")}">{("+" if total > 0 else "")}{n(total)}</td>
</tr>''')

    qty_t = sum(i["qty_imp"] for i in items)
    price_t = sum(i["price_imp"] for i in items)
    new_t = sum(i["new_imp"] for i in items)
    stop_t = sum(i["stop_imp"] for i in items)
    data_json = json.dumps(rows_js, ensure_ascii=False)

    html = f'''<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>采购差额归因分析</title>
<style>
:root {{
  --bg:#f5f7fa; --card:#ffffff; --ink:#1f2937; --muted:#6b7280; --line:#e5e7eb;
  --qty:#2563eb; --price:#d97706; --new:#059669; --stop:#dc2626;
}}
* {{ box-sizing:border-box; margin:0; padding:0; }}
body {{ font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;
  background:var(--bg); color:var(--ink); padding:24px; }}
.wrap {{ max-width:1180px; margin:0 auto; }}
h1 {{ font-size:22px; margin-bottom:4px; }}
.sub {{ color:var(--muted); font-size:13px; margin-bottom:18px; }}
.cards {{ display:flex; gap:12px; flex-wrap:wrap; margin-bottom:18px; }}
.card {{ flex:1; min-width:150px; background:var(--card); border:1px solid var(--line);
  border-radius:10px; padding:14px 16px; }}
.card .k {{ font-size:12px; color:var(--muted); }}
.card .v {{ font-size:22px; font-weight:700; margin-top:4px; }}
.v.pos {{ color:var(--new); }} .v.neg {{ color:var(--stop); }}
.toolbar {{ display:flex; gap:8px; margin-bottom:12px; align-items:center; flex-wrap:wrap; }}
.toolbar .label {{ font-size:13px; color:var(--muted); }}
.btn {{ border:1px solid var(--line); background:var(--card); border-radius:999px;
  padding:6px 16px; font-size:13px; cursor:pointer; }}
.btn.active {{ background:#1f4e79; color:#fff; border-color:#1f4e79; }}
.card-lg {{ background:var(--card); border:1px solid var(--line); border-radius:10px; overflow:hidden; }}
table {{ width:100%; border-collapse:collapse; font-size:13px; }}
th {{ background:#f0f4f8; padding:9px 8px; text-align:left; font-weight:600;
  border-bottom:2px solid var(--line); white-space:nowrap; }}
td {{ padding:10px 8px; border-bottom:1px solid var(--line); vertical-align:top; }}
tr:last-child td {{ border-bottom:none; }}
.num {{ text-align:right; white-space:nowrap; font-variant-numeric:tabular-nums; }}
.num.pos {{ color:var(--new); font-weight:600; }}
.num.neg {{ color:var(--stop); font-weight:600; }}
.sku {{ font-weight:700; }}
.tag {{ display:inline-block; font-size:11px; padding:1px 8px; border-radius:999px; margin-left:4px; }}
.tag-same {{ background:#e0ecff; color:#2563eb; }}
.tag-new {{ background:#d9f2e5; color:#059669; }}
.tag-stop {{ background:#fde3e3; color:#dc2626; }}
.chart {{ min-width:340px; }}
.bar-row {{ display:flex; align-items:center; gap:6px; margin:2px 0; }}
.bar-label {{ width:30px; font-size:11px; color:var(--muted); flex:none; }}
.bar-track {{ flex:1; height:12px; background:#f1f5f9; border-radius:3px; overflow:hidden; }}
.bar {{ height:100%; border-radius:3px; min-width:2px; }}
.seg-qty {{ background:var(--qty); }}
.seg-price {{ background:var(--price); }}
.seg-new {{ background:var(--new); }}
.seg-stop {{ background:var(--stop); }}
.bar-neg {{ background:repeating-linear-gradient(45deg,rgba(0,0,0,.18) 0 3px,transparent 3px 6px); }}
.bar-val {{ width:64px; text-align:right; font-size:12px; font-variant-numeric:tabular-nums; flex:none; }}
.total-cell {{ font-weight:700; }}
.legend {{ display:flex; gap:14px; flex-wrap:wrap; margin:12px 2px 0; font-size:12px; color:var(--muted); }}
.legend i {{ display:inline-block; width:12px; height:12px; border-radius:3px; margin-right:5px; vertical-align:-1px; }}
.note {{ margin-top:14px; font-size:12px; color:var(--muted); line-height:1.7; }}
tfoot td {{ background:#fdf6e3; font-weight:700; border-top:2px solid #d8c98a; }}
.hidden {{ display:none; }}
</style>
</head>
<body>
<div class="wrap">
  <h1>采购差额归因分析（上月 → 本月）</h1>
  <div class="sub">含税人民币 · 按 SKU 匹配 · 同品：数量影响=(本月量−上月量)×上月价，价格影响=本月量×(本月价−上月价)；新品列本月全额，停采列负上月全额</div>

  <div class="cards">
    <div class="card"><div class="k">上月采购总额</div><div class="v">{n(prev_total)} 元</div></div>
    <div class="card"><div class="k">本月采购总额</div><div class="v">{n(curr_total)} 元</div></div>
    <div class="card"><div class="k">总差额（本月−上月）</div><div class="v pos">{n(diff)} 元</div></div>
    <div class="card"><div class="k">数量影响合计</div><div class="v pos">{("+" if qty_t>=0 else "")}{n(qty_t)}</div></div>
    <div class="card"><div class="k">价格影响合计</div><div class="v pos">{("+" if price_t>=0 else "")}{n(price_t)}</div></div>
    <div class="card"><div class="k">新品影响合计</div><div class="v pos">{("+" if new_t>=0 else "")}{n(new_t)}</div></div>
    <div class="card"><div class="k">停采影响合计</div><div class="v neg">{n(stop_t)}</div></div>
  </div>

  <div class="toolbar">
    <span class="label">筛选：</span>
    <button class="btn active" data-f="all">全部</button>
    <button class="btn" data-f="同品">同品</button>
    <button class="btn" data-f="新增">新增</button>
    <button class="btn" data-f="停采">停采</button>
    <span class="label" id="count"></span>
  </div>

  <div class="card-lg">
  <table id="tbl">
    <thead><tr>
      <th>SKU</th><th>名称</th>
      <th colspan="3" style="text-align:center">上月</th>
      <th colspan="3" style="text-align:center">本月</th>
      <th></th><th>影响分解（离线条形图）</th><th style="text-align:right">影响合计</th>
    </tr>
    <tr>
      <th></th><th></th>
      <th class="num">数量</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 class="num">元</th>
    </tr></thead>
    <tbody>{"".join(rows_html)}</tbody>
    <tfoot><tr>
      <td colspan="2">合计（随筛选更新）</td>
      <td class="num" id="f-pq"></td><td></td><td class="num" id="f-pa"></td>
      <td class="num" id="f-cq"></td><td></td><td class="num" id="f-ca"></td>
      <td></td>
      <td class="num" style="font-size:12px">数量 <span id="f-qty"></span> / 价格 <span id="f-price"></span> / 新品 <span id="f-new"></span> / 停采 <span id="f-stop"></span></td>
      <td class="num" id="f-total"></td>
    </tr></tfoot>
  </table>
  </div>

  <div class="legend">
    <span><i style="background:var(--qty)"></i>数量影响</span>
    <span><i style="background:var(--price)"></i>价格影响</span>
    <span><i style="background:var(--new)"></i>新品影响</span>
    <span><i style="background:var(--stop)"></i>停采影响</span>
    <span><i style="background:repeating-linear-gradient(45deg,#999 0 3px,transparent 3px 6px)"></i>斜纹 = 负值</span>
  </div>

  <div class="note">
    口径：同品数量影响=(本月量−上月量)×上月价；价格影响=本月量×(本月价−上月价)。新品全额列新品影响，停采负上月全额列停采影响，不把交叉项计算两次。
    校验：本月总额 − 上月总额 = {n(curr_total)} − {n(prev_total)} = {n(diff)}，与数量/价格/新品/停采影响之和完全一致。
  </div>
</div>

<script>
const DATA = {data_json};
let filter = "all";
function fmt(v) {{
  const a = Math.abs(v);
  if (a < 1e-9) return "0";
  const body = a.toFixed(2).replace(/\\.?0+$/, "") || "0";
  return (v < 0 ? "-" : "+") + body;
}}
function render() {{
  const rows = DATA.filter(d => filter === "all" || d.type === filter);
  document.querySelectorAll("tr.item").forEach(tr => {{
    tr.classList.toggle("hidden", !(filter === "all" || tr.dataset.type === filter));
  }});
  const sum = k => rows.reduce((a, d) => a + d[k], 0);
  const pq = sum("pq"), pa = sum("pa"), cq = sum("cq"), ca = sum("ca");
  const tq = sum("qty"), tp = sum("price"), tn = sum("new"), ts = sum("stop"), tt = sum("total");
  document.getElementById("f-pq").textContent = pq.toFixed(2).replace(/\\.?0+$/, "");
  document.getElementById("f-pa").textContent = pa.toFixed(2).replace(/\\.?0+$/, "");
  document.getElementById("f-cq").textContent = cq.toFixed(2).replace(/\\.?0+$/, "");
  document.getElementById("f-ca").textContent = ca.toFixed(2).replace(/\\.?0+$/, "");
  document.getElementById("f-qty").textContent = fmt(tq);
  document.getElementById("f-price").textContent = fmt(tp);
  document.getElementById("f-new").textContent = fmt(tn);
  document.getElementById("f-stop").textContent = fmt(ts);
  const el = document.getElementById("f-total");
  el.textContent = fmt(tt);
  el.className = "num total-cell " + (tt > 0 ? "pos" : tt < 0 ? "neg" : "");
  document.getElementById("count").textContent =
    `当前 ${{rows.length}} 项 · 影响合计 ${{fmt(tt)}} 元`;
}}
document.querySelectorAll(".btn").forEach(b => b.addEventListener("click", () => {{
  document.querySelectorAll(".btn").forEach(x => x.classList.remove("active"));
  b.classList.add("active");
  filter = b.dataset.f;
  render();
}}));
render();
</script>
</body>
</html>'''
    path = os.path.join(OUT, "采购分析.html")
    with open(path, "w", encoding="utf-8") as f:
        f.write(html)
    print("写出:", path)

# ---------- 6. 核算说明.md ----------
def write_md(items, prev_total, curr_total, diff):
    lines = [
        "# 核算说明 — 采购差额归因（W02）",
        "",
        "## 一、口径（依据 inputs/口径.md）",
        "",
        "- 含税人民币；按 SKU 匹配两期数据。",
        "- 同品：**数量影响 = (本月量 − 上月量) × 上月价**；**价格影响 = 本月量 × (本月价 − 上月价)**。",
        "- 新品（上月无、本月有）：本月金额全额列新品影响。",
        "- 停采（上月有、本月无）：负上月金额全额列停采影响。",
        "- 交叉项不重复计算：同品拆分为数量+价格两项，无重复计入。",
        "",
        "## 二、两期总览",
        "",
        f"| 期间 | 采购总额 |",
        f"|---|---|",
        f"| 上月 | {prev_total:g} 元 |",
        f"| 本月 | {curr_total:g} 元 |",
        f"| 差额（本月−上月） | **{diff:g} 元** |",
        "",
        "## 三、分项影响",
        "",
        "| SKU | 名称 | 类别 | 上月量×价 | 本月量×价 | 数量影响 | 价格影响 | 新品影响 | 停采影响 | 影响合计 |",
        "|---|---|---|---|---|---|---|---|---|---|",
    ]
    for i in items:
        t = i["qty_imp"] + i["price_imp"] + i["new_imp"] + i["stop_imp"]
        def s(v):
            return ("+" if v > 0 else "") + f"{v:g}" if v else "0"
        pv = f"{i['prev_qty']:g}×{i['prev_price']:g}" if i["prev_qty"] else "—"
        cv = f"{i['curr_qty']:g}×{i['curr_price']:g}" if i["curr_qty"] else "—"
        lines.append(f"| {i['sku']} | {i['name']} | {i['type']} | {pv} | {cv} | "
                     f"{s(i['qty_imp'])} | {s(i['price_imp'])} | {s(i['new_imp'])} | {s(i['stop_imp'])} | **{s(t)}** |")
    lines += [
        f"| 合计 | | | | | **{sum(i['qty_imp'] for i in items):+g}** | "
        f"**{sum(i['price_imp'] for i in items):+g}** | **{sum(i['new_imp'] for i in items):+g}** | "
        f"**{sum(i['stop_imp'] for i in items):+g}** | **{diff:+g}** |",
        "",
        "## 四、逐项计算过程",
        "",
    ]
    for i in items:
        if i["type"] == "同品":
            lines.append(
                f"- **{i['sku']} {i['name']}（同品）**：数量影响 = ({i['curr_qty']:g} − {i['prev_qty']:g}) × {i['prev_price']:g} = **{i['qty_imp']:+g}**；"
                f"价格影响 = {i['curr_qty']:g} × ({i['curr_price']:g} − {i['prev_price']:g}) = **{i['price_imp']:+g}**；合计 **{i['qty_imp'] + i['price_imp']:+g}**。")
        elif i["type"] == "新增":
            lines.append(f"- **{i['sku']} {i['name']}（新增）**：本月全额 {i['curr_qty']:g} × {i['curr_price']:g} = **+{i['new_imp']:g}**。")
        else:
            lines.append(f"- **{i['sku']} {i['name']}（停采）**：负上月全额 −({i['prev_qty']:g} × {i['prev_price']:g}) = **{i['stop_imp']:g}**。")
    lines += [
        "",
        "## 五、总量校验",
        "",
        f"- 本月总额 − 上月总额 = {curr_total:g} − {prev_total:g} = **{diff:g}**",
        f"- 数量影响 + 价格影响 + 新品影响 + 停采影响 = "
        f"{sum(i['qty_imp'] for i in items):+g} + {sum(i['price_imp'] for i in items):+g} + "
        f"{sum(i['new_imp'] for i in items):+g} + {sum(i['stop_imp'] for i in items):+g} = **{diff:g}**",
        "- 两者一致 ✓（总差额 = 全部影响之和）",
        "",
        "## 六、交付物",
        "",
        "| 文件 | 内容 |",
        "|---|---|",
        "| 采购归因.csv | 纯数字明细（两期数量/单价/金额 + 四类影响），UTF-8 BOM，可直接独立核算 |",
        "| 采购归因.xlsx | 同一明细的 Excel 版，含新增/停采底色标识与校验行 |",
        "| 采购分析.html | 离线 CSS 条形图 + 全部/同品/新增/停采筛选，合计随筛选更新 |",
        "| 核算说明.md | 本说明 |",
        "| generate.py / README.md | 可重复运行脚本与说明 |",
        "",
        "---",
        "",
        "*本目录交付物由 generate.py 生成（AI 辅助产出，文件属性可标识）。*",
    ]
    path = os.path.join(OUT, "核算说明.md")
    with open(path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")
    print("写出:", path)

# ---------- 7. README.md ----------
def write_readme(prev_total, curr_total, diff):
    txt = f"""# W02 采购差额归因 — 交付说明

## 任务
上月/本月两期采购（合成数据，含税人民币，按 SKU 匹配），将总差额归因到
数量、价格、新品、停采四类影响；总差额必须等于全部影响之和。

## 口径（inputs/口径.md）
- 同品：数量影响 = (本月量 − 上月量) × 上月价；价格影响 = 本月量 × (本月价 − 上月价)
- 新品：本月全额列新品影响；停采：负上月全额列停采影响
- 交叉项不重复计算

## 核算结果
- 上月总额 {prev_total:g} 元；本月总额 {curr_total:g} 元；总差额 {diff:g} 元
- 数量影响 + 价格影响 + 新品影响 + 停采影响 = {diff:g} 元，与总差额一致 ✓

## 文件清单（均为 AI 辅助产出，见文件属性）
| 文件 | 说明 |
|---|---|
| 采购归因.csv | 纯数字明细，含合计行，可独立核算 |
| 采购归因.xlsx | Excel 明细（新增/停采底色 + 校验行） |
| 采购分析.html | 离线 CSS 条形图；全部/同品/新增/停采筛选，合计随筛选更新 |
| 核算说明.md | 口径、逐项计算过程与总量校验 |
| generate.py | 可重复运行生成脚本（重新生成全部成品） |
| README.md | 本说明 |

## 重新生成
```bash
/Users/macmini_no1/.cache/codex-runtimes/codex-primary-runtime/dependencies/python/bin/python3 generate.py
```
脚本从 `../inputs/` 只读原始数据，全部成品写回本目录；inputs 目录不做任何修改。

## 自检
脚本内置断言：总差额 == 四类影响之和（不一致则报错退出）。
"""
    path = os.path.join(OUT, "README.md")
    with open(path, "w", encoding="utf-8") as f:
        f.write(txt)
    print("写出:", path)

# ---------- main ----------
def main():
    prev, curr = read_inputs()
    items, diff = compute(prev, curr)
    prev_total = sum(i["prev_amt"] for i in items)
    curr_total = sum(i["curr_amt"] for i in items)
    write_csv(items, prev_total, curr_total, diff)
    write_xlsx(items, prev_total, curr_total, diff)
    write_html(items, prev_total, curr_total, diff)
    write_md(items, prev_total, curr_total, diff)
    write_readme(prev_total, curr_total, diff)
    print(f"\n校验通过: 总差额 {diff:g} = 数量+价格+新品+停采影响之和")

if __name__ == "__main__":
    main()
