#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""W04 产出静态检查与测试。

校验内容：
  1. inputs 未被改动（与 input-sha256.json 哈希一致）
  2. 补货建议.csv 数值与口径重算一致，且符合期望夹具
  3. 补货建议.xlsx 可打开、行列值一致，含口径说明页
  4. 补货看板.html 含三个筛选、合计随筛选更新的元素、无下单功能、含 aigc 标记
  5. 三件套文件属性含 aigc = AI-generated

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

import csv
import hashlib
import json
import re
import subprocess
import sys
from pathlib import Path

BASE = Path(__file__).resolve().parent
ROOT = BASE.parent
INPUTS = ROOT / "inputs"
HASH_JSON = ROOT / "input-sha256.json"

sys.path.insert(0, str(BASE))
import generate  # noqa: E402

FAILURES: list[str] = []


def check(name: str, cond: bool, detail: str = "") -> None:
    status = "PASS" if cond else "FAIL"
    print(f"[{status}] {name}" + (f" — {detail}" if detail and not cond else ""))
    if not cond:
        FAILURES.append(f"{name}: {detail}")


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    h.update(path.read_bytes())
    return h.hexdigest()


def main() -> None:
    # 1. 输入只读：哈希校验
    expected = json.loads(HASH_JSON.read_text(encoding="utf-8"))
    for rel, digest in expected.items():
        p = ROOT / rel
        check(f"输入未改动 {rel}", p.exists() and sha256(p) == digest,
              f"actual={sha256(p) if p.exists() else 'missing'}")

    # 重算（与生成同源口径）
    rows = [generate.compute(r) for r in generate.load_rows()]
    by = {r["SKU"]: r for r in rows}

    # 期望夹具（独立于生成脚本的断言，双保险）
    fixtures = {
        "A": dict(日均=10.0, 可售=1.0, 目标=30.0, 净需求=20.0, 建议=24, 风险="是", 分类="需要补货"),
        "B": dict(日均=5.0, 可售=10.0, 目标=25.0, 净需求=0.0, 建议=0, 风险="否", 分类="库存充足"),
        "C": dict(日均=0.0, 可售=None, 目标=0.0, 净需求=0.0, 建议=0, 风险="不适用", 分类="零销量"),
        "D": dict(日均=10.0, 可售=0.0, 目标=30.0, 净需求=30.0, 建议=0, 风险="是", 分类="停销"),
        "E": dict(日均=3.0, 可售=2.0 / 3.0, 目标=9.0, 净需求=4.0, 建议=6, 风险="是", 分类="需要补货"),
        "F": dict(日均=2.0, 可售=0.0, 目标=4.0, 净需求=4.0, 建议=5, 风险="是", 分类="需要补货"),
    }
    for sku, fx in fixtures.items():
        r = by[sku]
        ok = (
            abs(r["日均"] - fx["日均"]) < 1e-9
            and ((fx["可售"] is None and r["可售天数"] is None)
                 or (fx["可售"] is not None and abs(r["可售天数"] - fx["可售"]) < 1e-9))
            and abs(r["目标"] - fx["目标"]) < 1e-9
            and abs(r["净需求"] - fx["净需求"]) < 1e-9
            and r["整箱建议"] == fx["建议"]
            and r["预计缺货风险"] == fx["风险"]
            and r["分类"] == fx["分类"]
        )
        check(f"夹具 {sku}", ok, json.dumps(fx, ensure_ascii=False))

    # 2. CSV
    csv_path = BASE / "补货建议.csv"
    check("CSV 存在", csv_path.exists())
    with csv_path.open("r", encoding="utf-8-sig", newline="") as f:
        csv_rows = list(csv.DictReader(f))
    check("CSV 行数=6", len(csv_rows) == 6, f"got {len(csv_rows)}")
    csv_by = {r["SKU"]: r for r in csv_rows}
    for sku, fx in fixtures.items():
        c = csv_by[sku]
        ok = (
            abs(float(c["日均"]) - fx["日均"]) < 1e-6
            and abs(float(c["目标"]) - fx["目标"]) < 1e-6
            and abs(float(c["净需求"]) - fx["净需求"]) < 1e-6
            and int(c["整箱建议"]) == fx["建议"]
            and c["预计缺货风险"] == fx["风险"]
            and c["分类"] == fx["分类"]
            and c["风险依据"].strip() != ""
            and c["计算链"].strip() != ""
        )
        if fx["可售"] is None:
            ok = ok and c["可售天数"] == "不适用"
        else:
            ok = ok and abs(float(c["可售天数"]) - fx["可售"]) < 0.01
        check(f"CSV {sku} 数值", ok, str(c))
    # 合计
    net_sum = sum(float(c["净需求"]) for c in csv_rows)
    sug_sum = sum(int(c["整箱建议"]) for c in csv_rows)
    check("CSV 合计 净需求=58", abs(net_sum - 58.0) < 1e-6, str(net_sum))
    check("CSV 合计 整箱建议=35", sug_sum == 35, str(sug_sum))

    # 3. XLSX
    xlsx_path = BASE / "补货建议.xlsx"
    check("XLSX 存在", xlsx_path.exists())
    try:
        from openpyxl import load_workbook
        wb = load_workbook(xlsx_path)
        check("XLSX 含「补货建议」页", "补货建议" in wb.sheetnames, str(wb.sheetnames))
        check("XLSX 含「口径说明」页", "口径说明" in wb.sheetnames, str(wb.sheetnames))
        ws = wb["补货建议"]
        header = [c.value for c in ws[1]]
        check("XLSX 表头完整", "整箱建议" in header and "风险依据" in header and "计算链" in header, str(header))
        check("XLSX 行数=6", ws.max_row == 7, f"max_row={ws.max_row}")
        idx = {name: header.index(name) + 1 for name in header}
        ok_x = True
        for i, fx_sku in enumerate(fixtures):
            sku = fx_sku
            row_i = i + 2
            fx = fixtures[sku]
            got = {
                "日均": ws.cell(row_i, idx["日均"]).value,
                "目标": ws.cell(row_i, idx["目标"]).value,
                "净需求": ws.cell(row_i, idx["净需求"]).value,
                "整箱建议": ws.cell(row_i, idx["整箱建议"]).value,
                "预计缺货风险": ws.cell(row_i, idx["预计缺货风险"]).value,
                "分类": ws.cell(row_i, idx["分类"]).value,
            }
            if not (
                abs(got["日均"] - fx["日均"]) < 1e-6
                and abs(got["目标"] - fx["目标"]) < 1e-6
                and abs(got["净需求"] - fx["净需求"]) < 1e-6
                and got["整箱建议"] == fx["建议"]
                and got["预计缺货风险"] == fx["风险"]
                and got["分类"] == fx["分类"]
            ):
                ok_x = False
                print(f"    mismatch {sku}: {got}")
        check("XLSX 数值与夹具一致", ok_x)
        check("XLSX creator 标识 AI", (wb.properties.creator or "").find("AI") >= 0,
              str(wb.properties.creator))
    except Exception as exc:
        check("XLSX 可打开", False, str(exc))

    # 4. HTML
    html_path = BASE / "补货看板.html"
    check("HTML 存在", html_path.exists())
    page = html_path.read_text(encoding="utf-8")
    for token, name in [
        ('data-group="all"', "HTML 筛选按钮：全部"),
        ('data-group="replenish"', "HTML 筛选按钮：需要补货"),
        ('data-group="manual"', "HTML 筛选按钮：需人工判断"),
        ('id="kpi-count"', "HTML 合计元素 kpi-count"),
        ('id="kpi-net"', "HTML 合计元素 kpi-net"),
        ('id="kpi-suggest"', "HTML 合计元素 kpi-suggest"),
        ('id="t-net"', "HTML 表尾合计 t-net"),
        ('id="t-suggest"', "HTML 表尾合计 t-suggest"),
        ('render("all")', "HTML 初始渲染调用"),
        ('meta name="aigc"', "HTML aigc 元标记"),
    ]:
        check(name, token in page, f"missing {token}")
    # 无下单功能：不允许下单类按钮/链接/表单（说明文案除外）
    ui_order = re.findall(
        r"<(?:button|a|input|form)\b[^>]*>\s*[^<]*(?:下单|购买|结算|立即买)", page, re.I
    )
    ui_order += re.findall(r"checkout|placeOrder|add-to-cart|add_to_cart", page, re.I)
    check("HTML 无下单功能（无下单按钮/表单）", not ui_order, f"found {ui_order}")
    # 内嵌数据行数与分组计数
    m = re.search(r"const ROWS = (\[.*?\]);", page, re.S)
    check("HTML 内嵌 ROWS 数据", bool(m))
    if m:
        embedded = json.loads(m.group(1))
        check("HTML ROWS 行数=6", len(embedded) == 6, str(len(embedded)))
        g_rep = sum(1 for r in embedded if r["group"] == "replenish")
        g_man = sum(1 for r in embedded if r["group"] == "manual")
        check("HTML 需要补货=3", g_rep == 3, str(g_rep))
        check("HTML 需人工判断=2（停销+零销量）", g_man == 2, str(g_man))
        cats = {r["sku"]: r["category"] for r in embedded}
        check("HTML 停销/零销量独立状态", cats.get("D") == "停销" and cats.get("C") == "零销量", str(cats))

    # 5. 文件属性 AI 标记
    for p in [csv_path, xlsx_path, html_path]:
        try:
            out = subprocess.run(["xattr", "-p", "aigc", str(p)], capture_output=True, text=True)
            ok = out.returncode == 0 and "AI-generated" in out.stdout
            check(f"文件属性 aigc 标记 {p.name}", ok, out.stdout + out.stderr)
        except Exception as exc:
            check(f"文件属性 aigc 标记 {p.name}", False, str(exc))

    print()
    if FAILURES:
        print(f"== 共 {len(FAILURES)} 项失败 ==")
        for f in FAILURES:
            print(" -", f)
        sys.exit(1)
    print("== 全部检查通过 ==")


if __name__ == "__main__":
    main()
