#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
compare_clauses.py — 合同条款版本比较与审阅辅助（合成练习）

用法（离线运行，仅依赖 Python 3 标准库）：
    python3 compare_clauses.py --spec ../inputs/spec.json --out .
    python3 compare_clauses.py --spec ../inputs/spec.json --out . --acceptance-date 2026-12-31
    python3 compare_clauses.py --spec ../inputs/spec.json --out . --selfcheck-only

功能：
  1) 按条款 id 对齐改前/改后文本，生成逐条差异分类（实质修改/新增/删除/纯格式变化/未变）
  2) 原句并排定位：字符级差异高亮 + 差异位置定位
  3) 金额 / 绝对日期 / 相对期限 / 否定词（责任方向）逐项解释
  4) 义务日期表；尾款类相对期限依验收日计算，缺验收日期时绝不推算绝对付款日
  5) 待确认项清单
  6) 输出 HTML（中文界面、无 CDN、375px 可用）、CSV、Markdown，并执行自检

性质声明：本工具仅作合同版本文本比较与审阅辅助，所有材料为合成练习，
输出不构成法律意见；单纯文本差异不得作为法律结论使用。
"""

from __future__ import annotations

import argparse
import csv
import datetime as dt
import difflib
import html as html_mod
import json
import re
import sys
from pathlib import Path

# ---------------------------------------------------------------- 正则工具

AMOUNT_RE = re.compile(r"(\d+(?:\.\d+)?)\s*元")
DATE_RE = re.compile(r"(\d{4})年(\d{1,2})月(\d{1,2})日")
# 相对期限：30日内 / 15日 / 24个月 / 3年 等
REL_RE = re.compile(r"(\d+)\s*(个月|月|年|日)(内)?")
NEG_RE = re.compile(r"不承担|不负责|不予|不得|不能|不应|不再|不|未|无|非")
PCT_RE = re.compile(r"(\d+(?:\.\d+)?)\s*%")
PARTY_RE = re.compile(r"甲方|乙方|双方")

EXCLAIM = "（合成练习，文本审阅辅助，不构成法律意见）"


# ---------------------------------------------------------------- 文本抽取


def strip_ws(s: str) -> str:
    return re.sub(r"\s+", "", s or "")


def is_ws_only_change(a: str, b: str) -> bool:
    return a != b and strip_ws(a) == strip_ws(b)


def extract_amounts(text: str):
    """返回 [(原文, 数值)]，如 [('12000元', 12000.0)]"""
    out = []
    for m in AMOUNT_RE.finditer(text or ""):
        out.append((m.group(0), float(m.group(1))))
    return out


def extract_dates(text: str):
    """返回 [(原文, date|None, 位置)]"""
    out = []
    for m in DATE_RE.finditer(text or ""):
        y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
        try:
            date_val = dt.date(y, mo, d)
        except ValueError:
            date_val = None
        out.append((m.group(0), date_val, m.span()))
    return out


def extract_rel_periods(text: str):
    """返回 [{'raw','num','unit','inner'}]，unit ∈ {日,月,个月,年}
    注意：排除落在绝对日期内部的片段（如“2026年12月20日”中的“2026年/12月/20日”），避免与日期维度重复计数。
    """
    text = text or ""
    date_spans = [m.span() for m in DATE_RE.finditer(text)]
    out = []
    for m in REL_RE.finditer(text):
        s, e = m.span()
        if any(ds <= s and e <= de for ds, de in date_spans):
            continue
        out.append(
            {
                "raw": m.group(0),
                "num": int(m.group(1)),
                "unit": m.group(2),
                "inner": bool(m.group(3)),
                "span": m.span(),
            }
        )
    return out


def extract_negations(text: str):
    """返回文本中出现的否定/责任方向标记（去重保序）"""
    seen, out = set(), []
    for m in NEG_RE.finditer(text or ""):
        t = m.group(0)
        if t not in seen:
            seen.add(t)
            out.append(t)
    return out


def extract_pcts(text: str):
    return [(m.group(0), float(m.group(1))) for m in PCT_RE.finditer(text or "")]


def first_party(text: str):
    m = PARTY_RE.search(text or "")
    return m.group(0) if m else "—"


def fmt_date(d: dt.date) -> str:
    return f"{d.year}年{d.month}月{d.day}日"


# ---------------------------------------------------------------- 差异定位


def locate_changes(a: str, b: str):
    """字符级对齐，返回 [{'a':(i1,i2,txt), 'b':(j1,j2,txt)}]"""
    sm = difflib.SequenceMatcher(None, a or "", b or "", autojunk=False)
    spans = []
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag == "equal":
            continue
        spans.append(
            {
                "a": (i1, i2, (a or "")[i1:i2]),
                "b": (j1, j2, (b or "")[j1:j2]),
                "tag": tag,
            }
        )
    return spans


def highlight_pair(a: str, b: str):
    """返回（改前HTML片段, 改后HTML片段），差异处用 <mark> 高亮"""
    esc = lambda s: html_mod.escape(s, quote=False)
    sm = difflib.SequenceMatcher(None, a or "", b or "", autojunk=False)
    left, right = [], []
    for tag, i1, i2, j1, j2 in sm.get_opcodes():
        if tag == "equal":
            left.append(esc(a[i1:i2]))
            right.append(esc(b[j1:j2]))
        else:
            if i1 != i2:
                left.append('<mark class="del">%s</mark>' % esc(a[i1:i2]))
            if j1 != j2:
                right.append('<mark class="ins">%s</mark>' % esc(b[j1:j2]))
    return "".join(left), "".join(right)


# ---------------------------------------------------------------- 期限计算


def resolve_relative_due(anchor_name: str, anchor_date, num: int, unit: str):
    """
    相对期限 → 绝对日期。anchor_date 为 None 时必须返回 None（绝不编造绝对付款日）。
    返回 (date|None, 说明文字)
    """
    if anchor_date is None:
        return None, f"缺{anchor_name}日期，不推算绝对日期，仅保留相对表述"
    if unit in ("日",):
        due = anchor_date + dt.timedelta(days=num)
    elif unit in ("月", "个月"):
        month = anchor_date.month - 1 + num
        year = anchor_date.year + month // 12
        month = month % 12 + 1
        day = min(
            anchor_date.day,
            [31, 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28,
             31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1],
        )
        due = dt.date(year, month, day)
    elif unit == "年":
        due = anchor_date.replace(year=anchor_date.year + num)
    else:
        return None, f"未知单位 {unit}，不推算"
    return due, f"{anchor_name}{fmt_date(anchor_date)} + {num}{unit} → {fmt_date(due)}（按提供验收日推算）"


# ---------------------------------------------------------------- 分类与解释


def classify_pair(before: str, after: str):
    """返回 (category, dims, explanations)"""
    if before == after:
        return "未变", [], ["文本完全一致，无任何变化。"]

    if is_ws_only_change(before, after):
        spans = locate_changes(before, after)
        loc = "；".join(
            f"改前[{s['a'][0]}:{s['a'][1]}]「{s['a'][2]}」↔ 改后[{s['b'][0]}:{s['b'][1]}]「{s['b'][2]}」"
            for s in spans
        )
        return (
            "纯格式变化(空白)",
            ["格式(空格)"],
            [
                "仅空白字符差异（空格增删），归一化空白后文本完全相同，不涉及金额、日期、责任等实质内容。",
                f"定位：{loc}",
            ],
        )

    dims, expl = [], []

    # 金额
    b_amt, a_amt = extract_amounts(before), extract_amounts(after)
    if [v for _, v in b_amt] != [v for _, v in a_amt]:
        dims.append("金额")
        if b_amt and a_amt:
            b0, a0 = b_amt[0][1], a_amt[0][1]
            delta = a0 - b0
            pct = (delta / b0 * 100) if b0 else None
            pct_s = f"，{delta / b0 * 100:+.1f}%" if b0 else ""
            expl.append(
                f"金额：{'、'.join(t for t, _ in b_amt)} → {'、'.join(t for t, _ in a_amt)}"
                f"（{delta:+.0f}元{pct_s}）。合同价款数额发生实质变化，需核对是否与商务约定一致。"
            )
        else:
            expl.append(
                f"金额：改前 {'、'.join(t for t, _ in b_amt) or '无'} → "
                f"改后 {'、'.join(t for t, _ in a_amt) or '无'}（金额项增删）。"
            )

    # 绝对日期
    b_dt, a_dt = extract_dates(before), extract_dates(after)
    if [d for _, d, _ in b_dt] != [d for _, d, _ in a_dt]:
        dims.append("日期")
        if b_dt and a_dt and b_dt[0][1] and a_dt[0][1]:
            diff = (a_dt[0][1] - b_dt[0][1]).days
            direction = "延后" if diff > 0 else "提前"
            expl.append(
                f"日期：{b_dt[0][0]} → {a_dt[0][0]}（{direction}{abs(diff)}日）。"
                f"为绝对期限节点，直接影响履约时间表。"
            )
        else:
            expl.append(
                f"日期：改前 {'、'.join(t for t, _, _ in b_dt) or '无'} → "
                f"改后 {'、'.join(t for t, _, _ in a_dt) or '无'}。"
            )

    # 相对期限
    b_rel, a_rel = extract_rel_periods(before), extract_rel_periods(after)
    if [r["raw"] for r in b_rel] != [r["raw"] for r in a_rel]:
        dims.append("相对期限")
        if b_rel and a_rel and b_rel[0]["unit"] == a_rel[0]["unit"]:
            d0, d1 = b_rel[0]["num"], a_rel[0]["num"]
            delta = d1 - d0
            direction = "延长" if delta > 0 else "缩短"
            expl.append(
                f"相对期限：{b_rel[0]['raw']} → {a_rel[0]['raw']}（{direction}{abs(delta)}{a_rel[0]['unit']}）。"
            )
        else:
            expl.append(
                f"相对期限：改前 {'、'.join(r['raw'] for r in b_rel) or '无'} → "
                f"改后 {'、'.join(r['raw'] for r in a_rel) or '无'}。"
            )
        # 尾款/验收类相对期限：缺验收日不得编造绝对付款日
        if "验收" in before or "验收" in after:
            expl.append(
                "尾款类条款依验收日相对计算：本材料未提供验收日期，"
                "故不推算绝对付款日，仅保留“验收后 N 日内”的相对表述（详见义务日期表与待确认项）。"
            )

    # 否定词 / 责任变化
    b_neg, a_neg = extract_negations(before), extract_negations(after)
    if b_neg != a_neg:
        dims.append("否定词/责任变化")
        b_show = "、".join(b_neg) if b_neg else "无"
        a_show = "、".join(a_neg) if a_neg else "无"
        expl.append(f"否定词：改前标记【{b_show}】→ 改后标记【{a_show}】。")
        if b_neg and not a_neg:
            expl.append(
                "否定词被删除，责任表述由否定变为肯定（如“不承担”→“承担”），"
                "责任承担方向发生反转，属实质责任变化，须逐字确认是否为双方真实意思。"
            )
        elif a_neg and not b_neg:
            expl.append(
                "新增否定词，责任表述由肯定变为否定，责任承担方向发生反转，属实质责任变化。"
            )
        else:
            expl.append("否定/责任方向标记发生变化，请结合上下文确认责任分配是否改变。")

    # 其他实质文本
    if not dims:
        dims.append("其他文本")
        expl.append("存在实质文本差异，但未命中金额/日期/相对期限/否定词特征，请人工逐字确认。")

    return "实质修改", dims, expl


def explain_added(text: str):
    parts = ["新增条款：改前版本无对应条文，属新增义务/约定。"]
    amts = extract_amounts(text)
    pcts = extract_pcts(text)
    dts = extract_dates(text)
    rels = extract_rel_periods(text)
    # 弱否定单字（如“未交付”的“未”）不作为责任方向否定标记展示，避免误导
    negs = [t for t in extract_negations(text) if len(t) > 1 or t.startswith("不")]
    bits = []
    if amts:
        bits.append("金额 " + "、".join(t for t, _ in amts))
    if pcts:
        bits.append("比率 " + "、".join(t for t, _ in pcts))
    if dts:
        bits.append("日期 " + "、".join(t for t, _, _ in dts))
    if rels:
        bits.append("相对期限 " + "、".join(r["raw"] for r in rels))
    per = re.findall(r"每[^。，；]{0,6}日", text)
    if per:
        bits.append("计收频率 " + "、".join(per))
    if negs:
        bits.append("否定标记 " + "、".join(negs))
    if bits:
        parts.append("关键要素：" + "；".join(bits) + "。")
    parts.append(f"责任主体（首个出现）：{first_party(text)}。新增条款同样属于版本间实质差异，但与“原条款修改”分开列示。")
    return parts


# ---------------------------------------------------------------- 数据组装


def load_spec(path: Path):
    data = json.loads(path.read_text(encoding="utf-8"))
    before = {str(x["id"]): x.get("text", "") for x in data.get("before", [])}
    after = {str(x["id"]): x.get("text", "") for x in data.get("after", [])}
    note = data.get("note", "")
    return before, after, note


def build_records(before: dict, after: dict):
    records = []
    ids = list(before.keys()) + [i for i in after.keys() if i not in before]
    # 保持 id 顺序（数字优先）
    ids = sorted(set(ids), key=lambda x: (len(x), x))
    for cid in ids:
        b, a = before.get(cid), after.get(cid)
        if b is not None and a is None:
            cat, dims, expl = "删除", ["条文删除"], ["该条文在改后版本中被删除，请确认删除是否有意为之。"]
        elif b is None and a is not None:
            cat, dims, expl = "新增", ["新增"], explain_added(a)
        else:
            cat, dims, expl = classify_pair(b, a)
        h_left, h_right = highlight_pair(b or "", a or "")
        spans = locate_changes(b or "", a or "")
        loc_txt = "；".join(
            f"改前[{s['a'][0]}:{s['a'][1]}]「{s['a'][2] or '空'}」↔ 改后[{s['b'][0]}:{s['b'][1]}]「{s['b'][2] or '空'}」"
            for s in spans
        ) or "无字符差异"
        records.append(
            {
                "id": cid,
                "before": b,
                "after": a,
                "category": cat,
                "dims": dims,
                "explanations": expl,
                "hl_left": h_left,
                "hl_right": h_right,
                "locate": loc_txt,
                "b_amts": extract_amounts(b or ""),
                "a_amts": extract_amounts(a or ""),
                "b_dates": extract_dates(b or ""),
                "a_dates": extract_dates(a or ""),
                "b_rels": extract_rel_periods(b or ""),
                "a_rels": extract_rel_periods(a or ""),
                "b_negs": extract_negations(b or ""),
                "a_negs": extract_negations(a or ""),
            }
        )
    return records


def build_obligation_rows(records, acceptance_date=None):
    """义务日期表：尾款等相对期限仅在提供验收日时才推算绝对日期。"""
    rows = []
    for r in records:
        text = r["after"] or r["before"] or ""
        if not text:
            continue
        party = first_party(text)

        def time_bits(t_text, dates, rels):
            bits = [t for t, _, _ in dates] + [x["raw"] for x in rels]
            bits += re.findall(r"每[^。，；]{0,6}日", t_text or "")
            return bits

        b_time = time_bits(r["before"], r["b_dates"], r["b_rels"]) if r["before"] else []
        a_time = time_bits(r["after"], r["a_dates"], r["a_rels"]) if r["after"] else []
        b_time_s = "、".join(b_time) if b_time else "未约定时间"
        a_time_s = "、".join(a_time) if a_time else "未约定时间"

        anchor = "—"
        abs_note = "否"
        calc = "—"
        if r["a_dates"] or r["b_dates"]:
            anchor = "绝对日期（条款内写明）"
            abs_note = "是"
            calc = "可直接使用条款内日期"
        # 相对期限 + 验收起算
        rels = r["a_rels"] or r["b_rels"]
        if "验收" in text and rels:
            anchor = "验收日"
            rel = rels[0]
            due, note = resolve_relative_due("验收日", acceptance_date, rel["num"], rel["unit"])
            if due is not None:
                abs_note = "是（按所给验收日推算）"
                calc = note
            else:
                abs_note = "否"
                calc = (
                    f"依验收日相对计算（{rel['raw']}）；未提供验收日期，"
                    "不推算绝对付款日，仅保留相对表述"
                )
        elif rels and anchor == "—":
            anchor = f"起算点未写明（期限 {rels[0]['raw']}）"
            abs_note = "否"
            calc = "缺起算点，不推算绝对日期"

        note_extra = ""
        if r["category"] == "未变":
            note_extra = "与改前一致"
        elif r["category"] == "新增":
            note_extra = "新增条款"
        elif r["category"] == "实质修改":
            note_extra = "实质修改：" + "、".join(r["dims"])

        rows.append(
            {
                "条款ID": r["id"],
                "义务/事项": text,
                "责任方(文本所见)": party,
                "时间要求(修订后)": "、".join(a_time) if a_time else "未约定时间",
                "时间要求(修订前)": b_time_s if (r["before"] and b_time) else ("改前无此条" if r["before"] is None else "未约定时间"),
                "起算点": anchor,
                "可否直接得到绝对日期": abs_note,
                "推算/说明": calc,
                "备注": note_extra,
            }
        )
    return rows


def build_pending_items(records, acceptance_date=None):
    items = []

    def add(rel, matter, reason, impact):
        items.append({"序号": str(len(items) + 1), "关联条款": rel, "待确认事项": matter, "原因": reason, "影响": impact})

    # 1) 缺验收日期
    rel_ids = [r["id"] for r in records if "验收" in (r["after"] or r["before"] or "") and (r["a_rels"] or r["b_rels"])]
    if rel_ids and acceptance_date is None:
        add(
            "、".join(rel_ids),
            "验收日期缺失，尾款绝对付款日不推算",
            "条款以“验收后 N 日内”约定付款期限，材料未提供验收日期",
            "只能保留相对期限（修订后为验收后15日内，修订前为30日内）；严禁臆造绝对付款日",
        )

    # 2) 保修起算点
    for r in records:
        text = r["after"] or r["before"] or ""
        if "保修" in text and not re.search(r"自(交付|验收|签署|生效)", text):
            add(
                r["id"],
                "保修期起算点未写明",
                f"条款仅写“保修期限为{extract_rel_periods(text)[0]['raw'] if extract_rel_periods(text) else '一定期限'}”，未约定自何时起算",
                "24个月的届满日无法确定，与验收/交付日期联动关系待明确",
            )

    # 3) 违约金基数
    for r in records:
        text = r["after"] or r["before"] or ""
        if "未交付部分" in text or "违约金" in text:
            add(
                r["id"],
                "违约金基数与上限口径待确认",
                "新增条款以“未交付部分金额”为基数按日 0.1% 计违约金，未写明基数认定方式与累计上限",
                "逾期责任金额可能随口径不同而显著变化，建议在签署前书面明确",
            )

    # 4) 附件未随附
    for r in records:
        text = r["after"] or r["before"] or ""
        if "附件" in text:
            add(
                r["id"],
                "所指附件未随附",
                "条款以“附件为准”约定联系地址，但材料中未提供附件文本",
                "联系地址无法核对；该条本次仅为空格格式变化，不涉及实质权利义务",
            )

    # 5) 总价变动后的付款安排
    for r in records:
        if "金额" in r["dims"] and r["b_amts"] and r["a_amts"]:
            delta = r["a_amts"][0][1] - r["b_amts"][0][1]
            add(
                r["id"],
                "总价调整后的付款节点未写明",
                f"总价由{r['b_amts'][0][0]}调整为{r['a_amts'][0][0]}（{delta:+.0f}元），条款未同步约定付款时间/分期安排",
                "付款义务金额明确但履行时间不明确，易生争议",
            )

    # 6) 责任方向变化的后续结算
    for r in records:
        if any("否定词" in d for d in r["dims"]):
            add(
                r["id"],
                "责任承担方向反转后的结算安排待确认",
                "否定词删除使“不承担”变为“承担”，责任方向反转",
                "运输保险费用由谁实际支付、已付/预付部分如何结算与凭证要求未写明",
            )

    # 7) 新增条款与既有条款衔接
    for r in records:
        if r["category"] == "新增":
            add(
                r["id"],
                "新增违约金条款与既有交付条款的衔接",
                "新增逾期违约金条款与交付期限条款（含交付日修改）需配套适用",
                "逾期起算、与损失赔偿的关系、是否可并用等未写明",
            )

    return items


# ---------------------------------------------------------------- 输出：CSV


def write_csvs(out_dir: Path, records, ob_rows, pending):
    clause_csv = out_dir / "clause_diff.csv"
    fields = [
        "条款ID", "分类", "变化维度", "改前原文", "改后原文",
        "金额_改前", "金额_改后", "绝对日期_改前", "绝对日期_改后",
        "相对期限_改前", "相对期限_改后", "否定词_改前", "否定词_改后",
        "差异定位", "逐项解释",
    ]
    with clause_csv.open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        for r in records:
            w.writerow(
                {
                    "条款ID": r["id"],
                    "分类": r["category"],
                    "变化维度": "、".join(r["dims"]) or "—",
                    "改前原文": r["before"] or "（无此条）",
                    "改后原文": r["after"] or "（已删除）",
                    "金额_改前": "、".join(t for t, _ in r["b_amts"]) or "—",
                    "金额_改后": "、".join(t for t, _ in r["a_amts"]) or "—",
                    "绝对日期_改前": "、".join(t for t, _, _ in r["b_dates"]) or "—",
                    "绝对日期_改后": "、".join(t for t, _, _ in r["a_dates"]) or "—",
                    "相对期限_改前": "、".join(x["raw"] for x in r["b_rels"]) or "—",
                    "相对期限_改后": "、".join(x["raw"] for x in r["a_rels"]) or "—",
                    "否定词_改前": "、".join(r["b_negs"]) or "无",
                    "否定词_改后": "、".join(r["a_negs"]) or "无",
                    "差异定位": r["locate"],
                    "逐项解释": " ".join(r["explanations"]),
                }
            )

    ob_csv = out_dir / "obligation_schedule.csv"
    ob_fields = [
        "条款ID", "义务/事项", "责任方(文本所见)", "时间要求(修订后)", "时间要求(修订前)",
        "起算点", "可否直接得到绝对日期", "推算/说明", "备注",
    ]
    with ob_csv.open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.DictWriter(f, fieldnames=ob_fields)
        w.writeheader()
        for row in ob_rows:
            w.writerow(row)

    p_csv = out_dir / "pending_items.csv"
    p_fields = ["序号", "关联条款", "待确认事项", "原因", "影响"]
    with p_csv.open("w", encoding="utf-8-sig", newline="") as f:
        w = csv.DictWriter(f, fieldnames=p_fields)
        w.writeheader()
        for row in pending:
            w.writerow(row)


# ---------------------------------------------------------------- 输出：Markdown


def write_markdown(out_dir: Path, records, ob_rows, pending, note, acceptance_date=None):
    lines = []
    A = lines.append
    A("# 合同版本差异审阅报告（合成练习）")
    A("")
    A("> **性质声明**：本报告由 `compare_clauses.py` 自动生成，仅作合同版本文本比较与审阅辅助，**不构成法律意见**。所有材料为合成练习，不用于签约。单纯文本差异（尤其纯格式差异）不得称为法律意见或法律结论。")
    A("")
    if note:
        A(f"> 输入备注：{note}")
    A("")
    if acceptance_date:
        A(f"> 本次运行提供的验收日期：{acceptance_date}（用于尾款相对期限推算）")
    else:
        A("> 本次运行**未提供验收日期**：尾款等“验收后 N 日内”条款只保留相对期限，**不推算绝对付款日**。")
    A("")

    # 分类统计
    order = ["实质修改", "新增", "删除", "纯格式变化(空白)", "未变"]
    counts = {k: 0 for k in order}
    for r in records:
        counts[r["category"]] = counts.get(r["category"], 0) + 1
    A("## 一、分类总览")
    A("")
    A("| 分类 | 数量 | 条款ID |")
    A("| --- | --- | --- |")
    for k in order:
        ids = "、".join(r["id"] for r in records if r["category"] == k) or "—"
        A(f"| {k} | {counts.get(k, 0)} | {ids} |")
    A("")
    A("其中「实质修改」按变化维度细分：")
    A("")
    dim_count = {}
    for r in records:
        if r["category"] == "实质修改":
            for d in r["dims"]:
                dim_count[d] = dim_count.get(d, 0) + 1
    for d, c in sorted(dim_count.items()):
        ids = "、".join(r["id"] for r in records if r["category"] == "实质修改" and d in r["dims"])
        A(f"- **{d}**：{c} 处（条款 {ids}）")
    A("")

    A("## 二、逐条原句并排对照与解释")
    A("")
    for r in records:
        A(f"### 条款 {r['id']} · {r['category']}"
          + (f"（{'、'.join(r['dims'])}）" if r["dims"] else ""))
        A("")
        A(f"- **改前原文**：{r['before'] if r['before'] is not None else '（无此条）'}")
        A(f"- **改后原文**：{r['after'] if r['after'] is not None else '（已删除）'}")
        A(f"- **差异定位**：{r['locate']}")
        A("- **逐项解释**：")
        for e in r["explanations"]:
            A(f"  - {e}")
        A("")

    A("## 三、义务日期表")
    A("")
    A("| 条款ID | 义务/事项 | 责任方(文本所见) | 时间要求(修订后) | 时间要求(修订前) | 起算点 | 可否直接得到绝对日期 | 推算/说明 | 备注 |")
    A("| --- | --- | --- | --- | --- | --- | --- | --- | --- |")
    for row in ob_rows:
        A("| " + " | ".join(
            str(row[k]).replace("\n", " ").replace("|", "\\|")
            for k in ["条款ID", "义务/事项", "责任方(文本所见)", "时间要求(修订后)",
                      "时间要求(修订前)", "起算点", "可否直接得到绝对日期", "推算/说明", "备注"]
        ) + " |")
    A("")
    A("> **尾款处理规则**：尾款支付期限为“验收后 30 日内（修订前）/ 15 日内（修订后）”，依验收日相对计算。缺验收日期时**不得编造绝对付款日**，表中保持相对表述。")
    A("")

    A("## 四、待确认项")
    A("")
    A("| 序号 | 关联条款 | 待确认事项 | 原因 | 影响 |")
    A("| --- | --- | --- | --- | --- |")
    for row in pending:
        A("| " + " | ".join(str(row[k]).replace("|", "\\|") for k in ["序号", "关联条款", "待确认事项", "原因", "影响"]) + " |")
    A("")

    A("## 五、口径与限制")
    A("")
    A("- 本报告保留全部条款（含未变条款与纯格式变化条款），不因“无实质变化”而删除或省略原文。")
    A("- 分类口径：**实质修改**＝改前已有条款的实质内容变化（金额/日期/否定词·责任/相对期限等）；**新增**＝改前不存在的条文；**纯格式变化(空白)**＝仅空白字符差异；**未变**＝文本完全一致。")
    A("- “否定词/责任变化”仅描述文本表述方向的改变，是否产生法律后果须由专业人士结合完整合同判断——本报告不作法律结论。")
    A("- 所有材料为合成练习；输出仅可用于流程演练与审阅辅助。")
    A("")
    (out_dir / "diff_report.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


# ---------------------------------------------------------------- 输出：HTML

CSS = """
:root{
  --bg:#f6f7f9; --card:#ffffff; --border:#e4e7ec; --text:#1f2937;
  --muted:#667085; --accent:#1d4ed8; --del-bg:#ffd9d6; --ins-bg:#c9f2cf;
  --warn-bg:#fff6e0; --chip:#eef2ff;
}
*{box-sizing:border-box;}
html,body{margin:0;padding:0;}
body{
  background:var(--bg); color:var(--text);
  font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Noto Sans CJK SC",sans-serif;
  font-size:15px; line-height:1.65;
  -webkit-text-size-adjust:100%;
}
.wrap{max-width:1080px; margin:0 auto; padding:16px 14px 48px;}
header.hero{background:var(--card); border:1px solid var(--border); border-radius:12px; padding:18px 16px; margin-bottom:14px;}
header.hero h1{margin:0 0 6px; font-size:21px; line-height:1.35;}
header.hero p{margin:4px 0; color:var(--muted); font-size:13px;}
.badge{display:inline-block; background:var(--chip); color:var(--accent); border-radius:999px; padding:2px 10px; font-size:12px; margin-right:6px;}
.section{background:var(--card); border:1px solid var(--border); border-radius:12px; padding:16px 14px; margin-bottom:14px;}
.section h2{margin:0 0 10px; font-size:17px;}
.section h3{margin:16px 0 8px; font-size:15px;}
.cards{display:flex; flex-wrap:wrap; gap:8px;}
.card{flex:1 1 130px; min-width:120px; border:1px solid var(--border); border-radius:10px; padding:10px 12px; background:#fafbfc;}
.card .num{font-size:22px; font-weight:700; color:var(--accent);}
.card .lbl{font-size:12px; color:var(--muted);}
.tag{display:inline-block; font-size:12px; border-radius:6px; padding:1px 8px; margin:0 4px 4px 0; background:#f2f4f7; color:#344054; border:1px solid var(--border);}
.tag.mod{background:#fee9e7; color:#b42318; border-color:#fecdca;}
.tag.add{background:#e7f8ec; color:#067647; border-color:#abefc6;}
.tag.fmt{background:#fff6e0; color:#b54708; border-color:#fedf89;}
.tag.same{background:#eef2f6; color:#475467; border-color:#d0d5dd;}
.pair{
  display:grid; grid-template-columns:1fr 1fr; gap:8px; margin:8px 0 10px;
}
.pane{border:1px solid var(--border); border-radius:8px; padding:8px 10px; background:#fcfcfd; min-width:0;}
.pane .cap{font-size:12px; color:var(--muted); margin-bottom:4px;}
.pane .txt{word-break:break-word; overflow-wrap:anywhere; font-size:14px;}
mark{padding:0 2px; border-radius:3px;}
mark.del{background:var(--del-bg); text-decoration:line-through;}
mark.ins{background:var(--ins-bg);}
.loc{font-size:12px; color:var(--muted); word-break:break-all;}
ul.expl{margin:6px 0 0; padding-left:18px;}
ul.expl li{margin:3px 0; font-size:14px;}
table{width:100%; border-collapse:collapse; font-size:13px;}
th,td{border:1px solid var(--border); padding:6px 8px; text-align:left; vertical-align:top; word-break:break-word;}
th{background:#f2f4f7; font-weight:600;}
.tscroll{overflow-x:auto; -webkit-overflow-scrolling:touch;}
.note{background:var(--warn-bg); border:1px solid #fedf89; border-radius:8px; padding:10px 12px; font-size:13px;}
footer{color:var(--muted); font-size:12px; text-align:center; padding:8px 10px;}
code{background:#f2f4f7; padding:1px 5px; border-radius:4px; font-size:12px;}
@media (max-width:480px){
  body{font-size:14px;}
  .wrap{padding:10px 8px 36px;}
  header.hero h1{font-size:18px;}
  .pair{grid-template-columns:1fr 1fr; gap:6px;}
  .pane .txt{font-size:12.5px; line-height:1.6;}
  .pane{padding:6px 7px;}
  th,td{padding:5px 6px; font-size:12px;}
  .card{flex:1 1 46%; min-width:0;}
}
@media (max-width:360px){
  .pane .txt{font-size:12px;}
}
"""


def write_html(out_dir: Path, records, ob_rows, pending, note, acceptance_date=None):
    E = lambda s: html_mod.escape(str(s), quote=False)
    parts = []
    A = parts.append
    A('<!DOCTYPE html>')
    A('<html lang="zh-CN">')
    A("<head>")
    A('<meta charset="utf-8">')
    A('<meta name="viewport" content="width=device-width, initial-scale=1">')
    A("<title>合同版本差异审阅报告（合成练习）</title>")
    A("<style>" + CSS + "</style>")
    A("</head>")
    A("<body><div class=\"wrap\">")

    A('<header class="hero">')
    A("<h1>合同版本差异审阅报告（合成练习）</h1>")
    A('<p><span class="badge">文本审阅辅助</span><span class="badge">非法律意见</span><span class="badge">合成材料</span></p>')
    A(f"<p>来源：<code>inputs/spec.json</code> · 生成脚本：<code>compare_clauses.py</code> · 中文界面 · 离线可用（无 CDN / 无外部资源）</p>")
    if acceptance_date:
        A(f"<p>验收日期（用于相对推算）：{E(acceptance_date)}</p>")
    else:
        A("<p>未提供验收日期：尾款等“验收后 N 日内”条款只保留相对期限，<strong>不推算绝对付款日</strong>。</p>")
    if note:
        A(f"<p>输入备注：{E(note)}</p>")
    A("</header>")

    # 统计
    order = ["实质修改", "新增", "删除", "纯格式变化(空白)", "未变"]
    counts = {}
    for r in records:
        counts[r["category"]] = counts.get(r["category"], 0) + 1
    A('<section class="section"><h2>一、分类总览</h2><div class="cards">')
    label_map = {
        "实质修改": "原条款实质修改",
        "新增": "新增条款",
        "删除": "删除条款",
        "纯格式变化(空白)": "纯空格格式变化",
        "未变": "未变条款",
    }
    for k in order:
        ids = "、".join(r["id"] for r in records if r["category"] == k) or "—"
        A(
            f'<div class="card"><div class="num">{counts.get(k, 0)}</div>'
            f'<div class="lbl">{label_map.get(k, k)}（条款 {ids}）</div></div>'
        )
    A("</div>")
    dim_count = {}
    for r in records:
        if r["category"] == "实质修改":
            for d in r["dims"]:
                dim_count[d] = dim_count.get(d, 0) + 1
    A("<p>实质修改细分：" + "；".join(
        f"<strong>{E(d)}</strong> {c} 处" for d, c in sorted(dim_count.items())
    ) + "。</p>")
    A('<div class="note">保留全部条款：未变条款与纯格式变化条款同样列示原文，不因“无实质变化”而省略。'
      "单纯文本差异（尤其纯格式差异）<strong>不称为法律意见</strong>。</div>")
    A("</section>")

    # 逐条并排
    A('<section class="section"><h2>二、逐条原句并排定位与逐项解释</h2>')
    tag_cls = {"实质修改": "mod", "新增": "add", "纯格式变化(空白)": "fmt", "未变": "same", "删除": "mod"}
    for r in records:
        dim_s = "、".join(r["dims"])
        A(f'<h3>条款 {E(r["id"])} · <span class="tag {tag_cls.get(r["category"], "")}">{E(r["category"])}</span>'
          + (f'<span class="tag">{E(dim_s)}</span>' if dim_s else "") + "</h3>")
        A('<div class="pair">')
        A(f'<div class="pane"><div class="cap">改前（原句）</div><div class="txt">{r["hl_left"] or "（无此条）"}</div></div>')
        A(f'<div class="pane"><div class="cap">改后（原句）</div><div class="txt">{r["hl_right"] or "（已删除）"}</div></div>')
        A("</div>")
        A(f'<div class="loc">差异定位：{E(r["locate"])}</div>')
        A('<ul class="expl">')
        for e in r["explanations"]:
            A(f"<li>{E(e)}</li>")
        A("</ul>")
    A("</section>")

    # 义务日期表
    cols = ["条款ID", "义务/事项", "责任方(文本所见)", "时间要求(修订后)", "时间要求(修订前)",
            "起算点", "可否直接得到绝对日期", "推算/说明", "备注"]
    A('<section class="section"><h2>三、义务日期表</h2>')
    A('<div class="tscroll"><table><thead><tr>')
    for c in cols:
        A(f"<th>{E(c)}</th>")
    A("</tr></thead><tbody>")
    for row in ob_rows:
        A("<tr>")
        for c in cols:
            A(f"<td>{E(row[c])}</td>")
        A("</tr>")
    A("</tbody></table></div>")
    A('<div class="note">尾款处理规则：尾款支付期限为“验收后 30 日内（修订前）/ 15 日内（修订后）”，依验收日相对计算。'
      "缺验收日期时不得编造绝对付款日，表中保持相对表述。</div>")
    A("</section>")

    # 待确认项
    pcols = ["序号", "关联条款", "待确认事项", "原因", "影响"]
    A('<section class="section"><h2>四、待确认项</h2><div class="tscroll"><table><thead><tr>')
    for c in pcols:
        A(f"<th>{E(c)}</th>")
    A("</tr></thead><tbody>")
    for row in pending:
        A("<tr>")
        for c in pcols:
            A(f"<td>{E(row[c])}</td>")
        A("</tr>")
    A("</tbody></table></div></section>")

    # 口径
    A('<section class="section"><h2>五、口径与限制</h2><ul>')
    A("<li>分类口径：<strong>实质修改</strong>＝改前已有条款的实质内容变化（金额/日期/否定词·责任/相对期限等）；"
      "<strong>新增</strong>＝改前不存在的条文；<strong>纯格式变化(空白)</strong>＝仅空白字符差异；<strong>未变</strong>＝文本完全一致。</li>")
    A("<li>金额/日期/否定词/责任变化逐项解释由脚本从原文抽取计算，定位到字符区间，可回溯原文核对。</li>")
    A("<li>“否定词/责任变化”仅描述文本表述方向改变，不构成法律结论；是否产生法律后果须结合完整合同由专业人士判断。</li>")
    A("<li>所有材料为合成练习；本页面仅供流程演练与审阅辅助，不用于签约。</li>")
    A("</ul></section>")

    A(f"<footer>compare_clauses.py 生成 · 离线页面（无 CDN、无外部脚本）· 手机 375px 可用 · {EXCLAIM}</footer>")
    A("</div></body></html>")

    (out_dir / "diff_report.html").write_text("\n".join(parts) + "\n", encoding="utf-8")


# ---------------------------------------------------------------- 自检


def run_selfcheck(out_dir: Path, spec_path: Path, records, ob_rows, pending, before, after, acceptance_date=None):
    results = []

    def check(name, ok, detail=""):
        results.append((bool(ok), name, detail))

    # 1 输入解析
    check("输入解析", len(before) == 6 and len(after) == 7,
          f"before={len(before)} after={len(after)}（期望 6 / 7）")

    # 2 分类计数
    counts = {}
    for r in records:
        counts[r["category"]] = counts.get(r["category"], 0) + 1
    expect = {"实质修改": 4, "新增": 1, "纯格式变化(空白)": 1, "未变": 1}
    ok = all(counts.get(k, 0) == v for k, v in expect.items()) and counts.get("删除", 0) == 0
    check("分类计数", ok, f"实际 {counts}，期望 实质修改=4 新增=1 纯格式变化=1 未变=1 删除=0")

    by_id = {r["id"]: r for r in records}

    # 3 条款1 金额
    r1 = by_id.get("1")
    check("条款1 金额维度",
          r1 and "金额" in r1["dims"] and r1["b_amts"] and r1["a_amts"]
          and r1["b_amts"][0][1] == 12000 and r1["a_amts"][0][1] == 15000,
          f"改前{[t for t, _ in r1['b_amts'] if r1]} 改后{[t for t, _ in r1['a_amts'] if r1]}")

    # 4 条款2 日期
    r2 = by_id.get("2")
    bd = [d for _, d, _ in r2["b_dates"]] if r2 else []
    ad = [d for _, d, _ in r2["a_dates"]] if r2 else []
    check("条款2 日期维度",
          r2 and "日期" in r2["dims"] and bd and ad and (ad[0] - bd[0]).days == 5,
          f"{bd} → {ad}（延后 {(ad[0]-bd[0]).days if bd and ad else '?'} 日）")

    # 5 条款3 否定词
    r3 = by_id.get("3")
    has_neg_before = bool(r3["b_negs"]) and any(("不" in t) or ("未" in t) for t in r3["b_negs"]) if r3 else False
    check("条款3 否定词/责任维度",
          r3 and any("否定词" in d for d in r3["dims"])
          and has_neg_before and not r3["a_negs"],
          f"改前否定词{r3['b_negs'] if r3 else None} 改后{r3['a_negs'] if r3 else None}（改前含否定标记、改后不含，责任方向反转）")

    # 6 条款4 相对期限
    r4 = by_id.get("4")
    check("条款4 相对期限维度",
          r4 and "相对期限" in r4["dims"]
          and r4["b_rels"] and r4["a_rels"]
          and r4["b_rels"][0]["num"] == 30 and r4["a_rels"][0]["num"] == 15,
          f"{r4['b_rels'][0]['raw'] if r4 and r4['b_rels'] else '?'} → {r4['a_rels'][0]['raw'] if r4 and r4['a_rels'] else '?'}")

    # 7 尾款不编造绝对付款日
    if acceptance_date is None:
        tail_offenders = []
        for fname in ("diff_report.md", "diff_report.html"):
            p = out_dir / fname
            if not p.exists():
                tail_offenders.append(f"{fname} 缺失")
                continue
            for ln in p.read_text(encoding="utf-8").splitlines():
                if "尾款" in ln and DATE_RE.search(ln):
                    tail_offenders.append(f"{fname}: {ln.strip()[:60]}")
        # 义务表中的推算列
        for row in ob_rows:
            if "验收" in str(row["起算点"]) and DATE_RE.search(str(row["推算/说明"])):
                tail_offenders.append(f"obligation 推算列出现绝对日期: {row['推算/说明']}")
        check("缺验收日不编造尾款绝对付款日", not tail_offenders,
              "未发现臆造绝对付款日" if not tail_offenders else "; ".join(tail_offenders))
    else:
        check("提供验收日时可推算", True, f"acceptance_date={acceptance_date}（相对推算允许出绝对日）")

    # 8 保留全部条款
    md = (out_dir / "diff_report.md").read_text(encoding="utf-8") if (out_dir / "diff_report.md").exists() else ""
    missing = []
    for cid, t in list(before.items()) + [(k, v) for k, v in after.items() if k not in before]:
        if t and t not in md:
            missing.append(cid)
    check("Markdown 保留全部条款原文", not missing, f"缺失条款: {missing}" if missing else "7 条原文均在 diff_report.md 中")

    # 9 HTML 离线 & 375px
    hp = out_dir / "diff_report.html"
    html_txt = hp.read_text(encoding="utf-8") if hp.exists() else ""
    bad_refs = re.findall(r"(?:src|href)\s*=\s*[\"']https?://[^\"']+", html_txt)
    bad_refs += re.findall(r"@import\s+url\(", html_txt)
    check("HTML 无 CDN/外部资源", not bad_refs and "<script" not in html_txt, str(bad_refs) or "无外部 src/href/@import/script")
    check("HTML 含 viewport 适配", 'name="viewport"' in html_txt and "max-width:480px" in html_txt,
          "viewport + 480px 媒体查询（375px 可用）")

    # 10 CSV 完整
    cp = out_dir / "clause_diff.csv"
    row_cnt = 0
    if cp.exists():
        with cp.open(encoding="utf-8-sig") as f:
            row_cnt = sum(1 for _ in csv.DictReader(f))
    check("clause_diff.csv 行数", row_cnt == len(records) == 7, f"数据行 {row_cnt}，期望 7")
    check("obligation_schedule.csv 非空", (out_dir / "obligation_schedule.csv").exists() and len(ob_rows) >= 5,
          f"{len(ob_rows)} 行")
    check("pending_items.csv 非空", (out_dir / "pending_items.csv").exists() and len(pending) >= 4,
          f"{len(pending)} 行")

    # 11 解释覆盖维度
    dims_all = set()
    for r in records:
        dims_all.update(r["dims"])
    need = {"金额", "日期", "否定词/责任变化", "相对期限"}
    check("金额/日期/否定词/相对期限均有解释", need.issubset(dims_all), f"覆盖维度: {sorted(dims_all)}")

    # 汇总
    now = dt.datetime.now().astimezone().isoformat(timespec="seconds")
    lines = ["# W26 合同版本比较 · 自检报告", "",
             f"- 运行时间：{now}",
             "- 脚本：outputs/compare_clauses.py（Python 标准库，离线）",
             f"- 输入：{spec_path}（只读）",
             f"- 输出目录：{out_dir}",
             f"- 验收日期参数：{acceptance_date or '未提供（尾款不推算绝对付款日）'}",
             ""]
    passed = 0
    for ok, name, detail in results:
        lines.append(f"[{'PASS' if ok else 'FAIL'}] {name}" + (f" — {detail}" if detail else ""))
        passed += 1 if ok else 0
    lines.append("")
    lines.append(f"总计：{passed}/{len(results)} 通过" + (" ✓ 全部通过" if passed == len(results) else " ✗ 存在失败项"))
    lines.append("")
    lines.append("说明：自检覆盖分类计数（4 实质修改 / 1 新增 / 1 纯格式 / 1 未变）、金额、日期、否定词、相对期限抽取，")
    lines.append("以及“缺验收日不编造尾款绝对付款日”“全部条款保留”“HTML 无 CDN 且 375px 可用”“CSV 行数”等硬性要求。")
    report = "\n".join(lines) + "\n"
    (out_dir / "selfcheck_report.txt").write_text(report, encoding="utf-8")
    return passed, len(results), report


# ---------------------------------------------------------------- 主流程


def generate(spec_path: Path, out_dir: Path, acceptance_date=None):
    before, after, note = load_spec(spec_path)
    records = build_records(before, after)
    ob_rows = build_obligation_rows(records, acceptance_date)
    pending = build_pending_items(records, acceptance_date)
    write_csvs(out_dir, records, ob_rows, pending)
    write_markdown(out_dir, records, ob_rows, pending, note, acceptance_date)
    write_html(out_dir, records, ob_rows, pending, note, acceptance_date)
    return before, after, records, ob_rows, pending


def main(argv=None):
    ap = argparse.ArgumentParser(description="合同条款版本比较（合成练习，文本审阅辅助，非法律意见）")
    ap.add_argument("--spec", required=True, help="spec.json 路径（只读）")
    ap.add_argument("--out", required=True, help="输出目录（仅写此目录）")
    ap.add_argument("--acceptance-date", default=None,
                    help="验收日期 YYYY-MM-DD；不提供则尾款不推算绝对付款日")
    ap.add_argument("--selfcheck-only", action="store_true", help="仅运行自检（需已生成产物）")
    args = ap.parse_args(argv)

    spec_path = Path(args.spec).resolve()
    out_dir = Path(args.out).resolve()
    out_dir.mkdir(parents=True, exist_ok=True)

    acc = None
    if args.acceptance_date:
        y, m, d = map(int, args.acceptance_date.split("-"))
        acc = dt.date(y, m, d)

    if args.selfcheck_only:
        before, after, note = load_spec(spec_path)
        records = build_records(before, after)
        ob_rows = build_obligation_rows(records, acc)
        pending = build_pending_items(records, acc)
    else:
        before, after, records, ob_rows, pending = generate(spec_path, out_dir, acc)
        print(f"[生成] diff_report.html / diff_report.md / clause_diff.csv / "
              f"obligation_schedule.csv / pending_items.csv → {out_dir}")

    passed, total, report = run_selfcheck(out_dir, spec_path, records, ob_rows, pending, before, after, acc)
    print(f"[自检] {passed}/{total} 通过 → {out_dir / 'selfcheck_report.txt'}")
    for line in report.splitlines():
        if line.startswith("["):
            print(line)
    return 0 if passed == total else 1


if __name__ == "__main__":
    sys.exit(main())
