#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""可复用订单数据清洗器（赛博游园会第二批 D03）。

用法示例（不硬编码本机路径，目录由调用方传入）:

    python3 cleaner.py --input-dir inputs --output-dir outputs

行为规则（与 inputs/规则.md 一致，规则文本若存在于输入目录会一并写入报告）:

  1. 所有字段去除首尾空白。
  2. 日期接受 ``YYYY-MM-DD`` 或 ``YYYY/MM/DD``，并校验真实日期；统一输出 ``YYYY-MM-DD``。
  3. 金额去掉 ``￥``/``¥`` 与千分逗号，用 ``Decimal`` 四舍五入到分（ROUND_HALF_UP）。
  4. 负数金额仅当状态为 ``refund`` 时合法。
  5. 状态仅 ``paid`` / ``refund``。
  6. ``order_id`` 必填。
  7. 相同 ``order_id`` 且标准化后全行相同：保留首次，其余标记为 duplicate。
  8. 相同 ``order_id`` 但标准化后存在差异（冲突）：全部 quarantine，不选择任何一行。
  9. 无效行进入 quarantine，并记录该行所有已发现原因。
 10. 每个原始数据行在 audit.csv 中恰好出现一次，``source_row`` 为 CSV 物理记录序号
     （表头为第 1 行）。
 11. 不静默丢弃任何行。

输出（全部写入 --output-dir）:

  - clean.csv        通过清洗的行（标准化后）
  - quarantine.csv   被隔离的行（保留原始值 + 全部原因）
  - audit.csv        每个原始数据行恰好一次，含原始值、标准化值、去向与原因/变换
  - summary.json     机器可读汇总
  - 质量报告.html     自包含 HTML 质量报告

输出为确定性产物：同一输入多次运行，输出文件内容逐字节一致（不含时间戳、排序稳定）。
"""

from __future__ import annotations

import argparse
import csv
import datetime as _dt
import html
import json
import re
import sys
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from pathlib import Path

# 输入文件列名（表头经过去首尾空白后的标准名）。
COL_ORDER_ID = "order_id"
COL_DATE = "date"
COL_AMOUNT = "amount"
COL_STATUS = "status"
COLUMNS = [COL_ORDER_ID, COL_DATE, COL_AMOUNT, COL_STATUS]

# 状态合法值。
VALID_STATUS = {"paid", "refund"}

# 日期格式：YYYY-MM-DD 或 YYYY/MM/DD（分隔符必须前后一致，月/日两位）。
_DATE_RE = re.compile(r"^(\d{4})([-/])(\d{2})\2(\d{2})$")

# 千分位逗号与货币符号。
_CURRENCY_SYMBOLS = ("￥", "¥")

# 规则文件候选名（若存在则嵌入报告，纯展示/溯源，不影响清洗逻辑）。
_RULES_FILENAMES = ("规则.md", "rules.md", "RULES.md", "规则.txt")


class CleaningError(Exception):
    """清洗过程的可预期错误。"""


# --------------------------------------------------------------------------- #
# CSV 读取：逐物理行跟踪 source_row（表头为第 1 行）。
# --------------------------------------------------------------------------- #
def _iter_csv_records(text: str):
    """解析 CSV 文本，逐记录产出 ``(start_line, fields)``。

    ``start_line`` 为该记录起始的 1 基物理行号；正确处理引号字段、引号内换行、
    逗号与转义引号 ``""``。文本末尾无换行时也能正确收尾最后一条记录。
    若存在未闭合的引号（含中途吞并后续记录的情况），抛出 :class:`CleaningError`。
    """
    i = 0
    n = len(text)
    line = 1
    records = []
    while i < n:
        start = line
        fields = []
        field_chars = []
        in_quotes = False
        record_ended = False
        while i < n:
            ch = text[i]
            if in_quotes:
                if ch == '"':
                    if i + 1 < n and text[i + 1] == '"':
                        field_chars.append('"')
                        i += 2
                        continue
                    in_quotes = False
                    i += 1
                    continue
                if ch == "\n":
                    line += 1
                    field_chars.append(ch)
                    i += 1
                    continue
                if ch == "\r":
                    if i + 1 < n and text[i + 1] == "\n":
                        line += 1
                        field_chars.append("\n")
                        i += 2
                    else:
                        line += 1
                        field_chars.append("\n")
                        i += 1
                    continue
                field_chars.append(ch)
                i += 1
                continue

            # 不在引号内
            if ch == '"' and not field_chars:
                in_quotes = True
                i += 1
                continue
            if ch == ",":
                fields.append("".join(field_chars))
                field_chars = []
                i += 1
                continue
            if ch == "\n":
                fields.append("".join(field_chars))
                field_chars = []
                line += 1
                i += 1
                record_ended = True
                break
            if ch == "\r":
                fields.append("".join(field_chars))
                field_chars = []
                line += 1
                i += 2 if (i + 1 < n and text[i + 1] == "\n") else 1
                record_ended = True
                break
            field_chars.append(ch)
            i += 1

        if in_quotes:
            raise CleaningError(
                f"CSV 格式异常：第 {start} 行起始的记录存在未闭合的引号"
            )
        if not record_ended:
            fields.append("".join(field_chars))
        records.append((start, fields))

    # 若文本以换行结尾，最后一个换行已经产生最后一条记录；不再产生多余空记录。
    return records


def read_csv(path: Path):
    """读取 CSV 文件，返回 ``(header_list, records)``。

    ``records`` 为 ``(source_row, dict_of_raw_fields)`` 列表，按物理顺序排列。
    """
    text = path.read_text(encoding="utf-8-sig")
    if not text:
        raise CleaningError(f"输入文件为空: {path.name}")

    try:
        parsed = _iter_csv_records(text)
    except CleaningError as exc:
        raise CleaningError(f"{path.name}: {exc}") from exc
    if not parsed:
        raise CleaningError(f"输入文件无记录: {path.name}")

    # 去掉文件末尾纯空记录（由末尾换行产生的一个空字段）。
    while parsed and parsed[-1][1] == [""]:
        parsed.pop()

    header_line, header_fields = parsed[0]
    if header_line != 1:
        raise CleaningError(f"表头不在第 1 行: {path.name}")
    header = [h.strip() for h in header_fields]
    if header != COLUMNS:
        raise CleaningError(f"表头不符合预期 {COLUMNS}，实际为 {header}: {path.name}")

    records = []
    for source_row, fields in parsed[1:]:
        if len(fields) != len(COLUMNS):
            # 列数不符：记为一行原始文本，交由逐行校验产生“列数异常”原因。
            raw = {COL_ORDER_ID: "", COL_DATE: "", COL_AMOUNT: "", COL_STATUS: ""}
            raw["_malformed"] = True
            raw["_raw_line"] = ",".join(fields)
            records.append((source_row, raw))
            continue
        raw = {
            COL_ORDER_ID: fields[0],
            COL_DATE: fields[1],
            COL_AMOUNT: fields[2],
            COL_STATUS: fields[3],
        }
        records.append((source_row, raw))
    return header, records


# --------------------------------------------------------------------------- #
# 字段级标准化。
# --------------------------------------------------------------------------- #
def normalize_date(raw: str):
    """返回 ``(normalized_or_None, reason_category_or_None, detail)``。"""
    s = raw.strip()
    if s == "":
        return None, "日期缺失", "日期缺失"
    m = _DATE_RE.match(s)
    if not m:
        return None, "日期非法", f"日期格式非法:{s}"
    year, _sep, month, day = int(m.group(1)), m.group(2), int(m.group(3)), int(m.group(4))
    try:
        d = _dt.date(year, month, day)
    except ValueError:
        return None, "日期非法", f"日期非法:{s}"
    return d.isoformat(), None, ""


def normalize_amount(raw: str):
    """返回 ``(rounded_or_None, reason_category_or_None, detail, raw_value_or_None)``。

    去除 ``￥``/``¥`` 与千分逗号后解析，四舍五入到分。``raw_value`` 为舍入前的
    ``Decimal``，供负数合法性等必须在舍入前完成的判断使用。
    """
    s = raw.strip()
    if s == "":
        return None, "金额缺失", "金额缺失", None
    cleaned = s
    for sym in _CURRENCY_SYMBOLS:
        cleaned = cleaned.replace(sym, "")
    cleaned = cleaned.replace(",", "")
    cleaned = cleaned.strip()
    if cleaned == "":
        return None, "金额缺失", f"金额缺失(去符号后为空):{s}", None
    try:
        value = Decimal(cleaned)
    except InvalidOperation:
        return None, "金额非数字", f"金额非数字:{s}", None
    if not value.is_finite():
        return None, "金额非数字", f"金额非法(非有限数):{s}", None
    try:
        rounded = value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
    except InvalidOperation:
        # 例如 1e999：精度超出当前 Decimal 上下文，无法四舍五入到分，隔离而非崩溃。
        return None, "金额超出支持精度", f"金额超出支持精度:{s}", None
    return rounded, None, "", value


def normalize_status(raw: str):
    s = raw.strip()
    if s == "":
        return None, "状态缺失", "状态缺失"
    if s not in VALID_STATUS:
        return None, "状态非法", f"状态非法:{s}"
    return s, None, ""


def normalize_order_id(raw: str):
    s = raw.strip()
    if s == "":
        return None, "order_id缺失", "order_id缺失"
    return s, None, ""


def format_amount(value: Decimal) -> str:
    """金额统一输出为两位小数字符串。"""
    return str(value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP))


# --------------------------------------------------------------------------- #
# 单行标准化 + 变换记录。
# --------------------------------------------------------------------------- #
def standardize(raw: dict):
    """对一行原始数据执行标准化。

    返回 dict:
      normalized: 标准化后的字段（非法字段为 None）
      reasons: [(category, detail), ...]
      transforms: [str, ...] 已应用的标准化变换（可溯源）
    """
    reasons = []
    transforms = []

    raw_oid = raw.get(COL_ORDER_ID, "")
    oid_stripped = raw_oid.strip()
    if oid_stripped != raw_oid:
        transforms.append("order_id去首尾空白")
    order_id, cat, detail = normalize_order_id(raw_oid)
    if cat:
        reasons.append((cat, detail))

    raw_date = raw.get(COL_DATE, "")
    date_stripped = raw_date.strip()
    if date_stripped != raw_date:
        transforms.append("date去首尾空白")
    date_norm, cat, detail = normalize_date(raw_date)
    if cat:
        reasons.append((cat, detail))
    elif "/" in date_stripped:
        transforms.append(f"日期分隔符规范化:{date_stripped}→{date_norm}")

    raw_amount = raw.get(COL_AMOUNT, "")
    amount_stripped = raw_amount.strip()
    if amount_stripped != raw_amount:
        transforms.append("amount去首尾空白")
    amount_norm, cat, detail, amount_unrounded = normalize_amount(raw_amount)
    if cat:
        reasons.append((cat, detail))
    else:
        cleaned = amount_stripped
        for sym in _CURRENCY_SYMBOLS:
            if sym in cleaned:
                transforms.append(f"金额去人民币符号({sym})")
                cleaned = cleaned.replace(sym, "")
        if "," in cleaned:
            transforms.append("金额去千分逗号")
            cleaned = cleaned.replace(",", "")
        cleaned = cleaned.strip()
        if amount_norm != Decimal(cleaned):
            transforms.append(f"金额四舍五入到分:{cleaned}→{format_amount(amount_norm)}")
        elif format_amount(amount_norm) != cleaned:
            transforms.append(f"金额补齐2位小数:{cleaned}→{format_amount(amount_norm)}")

    raw_status = raw.get(COL_STATUS, "")
    status_stripped = raw_status.strip()
    if status_stripped != raw_status:
        transforms.append("status去首尾空白")
    status_norm, cat, detail = normalize_status(raw_status)
    if cat:
        reasons.append((cat, detail))

    # 跨字段校验：负数金额仅 refund 合法。必须在舍入前判负（-0.004 舍入后为 -0.00，
    # 若用舍入后值判断会错误放行）。
    if amount_unrounded is not None and amount_unrounded < 0 and status_norm == "paid":
        reasons.append(
            ("金额为负但状态非refund", f"金额为负({amount_unrounded})但状态为paid")
        )

    normalized = {
        COL_ORDER_ID: order_id,
        COL_DATE: date_norm,
        COL_AMOUNT: amount_norm,
        COL_STATUS: status_norm,
    }
    return {
        "normalized": normalized,
        "reasons": reasons,
        "transforms": transforms,
        "order_id": order_id,
        "valid": len(reasons) == 0,
    }


# --------------------------------------------------------------------------- #
# 核心清洗流水线。
# --------------------------------------------------------------------------- #
def clean_records(records):
    """对 ``[(source_row, raw_dict), ...]`` 执行清洗，返回结果 dict。

    ``records`` 必须已按物理顺序排列。
    """
    standardized = []  # 每项含 source_row / raw / norm 结果
    for source_row, raw in records:
        std = standardize(raw)
        standardized.append(
            {
                "source_row": source_row,
                "raw": raw,
                "normalized": std["normalized"],
                "reasons": std["reasons"],
                "transforms": std["transforms"],
                "order_id": std["order_id"],
                "valid": std["valid"],
            }
        )

    # 按 order_id 分组（仅对“字段级合法”的行做重复/冲突判定）。
    groups = {}
    for item in standardized:
        if item["valid"] and item["order_id"] is not None:
            groups.setdefault(item["order_id"], []).append(item)

    disposition = {}  # source_row -> disposition
    reasons = {s["source_row"]: list(s["reasons"]) for s in standardized}

    for oid, items in groups.items():
        if len(items) == 1:
            disposition[items[0]["source_row"]] = "clean"
            continue
        # 全行标准化后是否相同。
        key = lambda it: (
            it["normalized"][COL_ORDER_ID],
            it["normalized"][COL_DATE],
            format_amount(it["normalized"][COL_AMOUNT]),
            it["normalized"][COL_STATUS],
        )
        first = items[0]
        if all(key(it) == key(first) for it in items[1:]):
            # 保留首次，其余 duplicate。
            disposition[first["source_row"]] = "clean"
            for dup in items[1:]:
                disposition[dup["source_row"]] = "duplicate"
                reasons[dup["source_row"]].append(
                    ("重复", f"重复:标准化后与source_row={first['source_row']}相同")
                )
        else:
            # 冲突：全部 quarantine。
            involved = sorted(it["source_row"] for it in items)
            for it in items:
                disposition[it["source_row"]] = "quarantine"
                reasons[it["source_row"]].append(
                    ("order_id冲突", f"order_id冲突:{oid}(涉及source_row={','.join(map(str, involved))})")
                )

    # 字段级非法行一律 quarantine。
    for s in standardized:
        if not s["valid"]:
            disposition[s["source_row"]] = "quarantine"

    # 组装审计行（每个原始行恰好一次）。
    audit_rows = []
    clean_rows = []
    quarantine_rows = []
    duplicate_rows = []

    for s in standardized:
        disp = disposition.get(s["source_row"])
        # 兜底：不可能出现，但保证不静默丢行。
        if disp is None:
            disp = "quarantine"
            reasons[s["source_row"]].append(("未分类", "未分类兜底:应人工核查"))

        norm = s["normalized"]
        amount_str = format_amount(norm[COL_AMOUNT]) if norm[COL_AMOUNT] is not None else ""
        date_str = norm[COL_DATE] or ""
        oid_str = norm[COL_ORDER_ID] or ""
        status_str = norm[COL_STATUS] or ""

        audit_rows.append(
            {
                "source_row": s["source_row"],
                "raw_order_id": s["raw"].get(COL_ORDER_ID, ""),
                "raw_date": s["raw"].get(COL_DATE, ""),
                "raw_amount": s["raw"].get(COL_AMOUNT, ""),
                "raw_status": s["raw"].get(COL_STATUS, ""),
                COL_ORDER_ID: oid_str,
                COL_DATE: date_str,
                COL_AMOUNT: amount_str,
                COL_STATUS: status_str,
                "disposition": disp,
                "reasons": "; ".join(detail for _cat, detail in reasons[s["source_row"]]),
                "transformations": "; ".join(s["transforms"]),
                "_reason_categories": [cat for cat, _detail in reasons[s["source_row"]]],
            }
        )

        if disp == "clean":
            clean_rows.append(
                {
                    COL_ORDER_ID: oid_str,
                    COL_DATE: date_str,
                    COL_AMOUNT: amount_str,
                    COL_STATUS: status_str,
                    "source_row": s["source_row"],
                }
            )
        elif disp == "quarantine":
            quarantine_rows.append(
                {
                    "source_row": s["source_row"],
                    COL_ORDER_ID: s["raw"].get(COL_ORDER_ID, ""),
                    COL_DATE: s["raw"].get(COL_DATE, ""),
                    COL_AMOUNT: s["raw"].get(COL_AMOUNT, ""),
                    COL_STATUS: s["raw"].get(COL_STATUS, ""),
                    "reasons": "; ".join(detail for _cat, detail in reasons[s["source_row"]]),
                }
            )
        elif disp == "duplicate":
            duplicate_rows.append({"source_row": s["source_row"]})

    # 原因计数（按类别聚合）。
    reason_counts = {}
    for row in audit_rows:
        for cat in row["_reason_categories"]:
            reason_counts[cat] = reason_counts.get(cat, 0) + 1
    # 移除仅用于内部统计的字段。
    for row in audit_rows:
        row.pop("_reason_categories", None)

    total = len(standardized)
    return {
        "clean_rows": clean_rows,
        "quarantine_rows": quarantine_rows,
        "duplicate_rows": duplicate_rows,
        "audit_rows": audit_rows,
        "reason_counts": reason_counts,
        "counts": {
            "total": total,
            "clean": len(clean_rows),
            "duplicate": len(duplicate_rows),
            "quarantine": len(quarantine_rows),
        },
        "clean_order_ids": [r[COL_ORDER_ID] for r in clean_rows],
        "duplicate_source_rows": [r["source_row"] for r in duplicate_rows],
        "quarantine_source_rows": [r["source_row"] for r in quarantine_rows],
    }


# --------------------------------------------------------------------------- #
# 输出写入。
# --------------------------------------------------------------------------- #
def _write_csv(path: Path, fieldnames, rows):
    with path.open("w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore")
        writer.writeheader()
        for row in rows:
            writer.writerow(row)


def _load_rules(input_dir: Path):
    for name in _RULES_FILENAMES:
        p = input_dir / name
        if p.is_file():
            return p.name, p.read_text(encoding="utf-8-sig").strip()
    return None, ""


def render_html(result, input_files, rules_name, rules_text):
    """生成自包含 HTML 质量报告。"""
    counts = result["counts"]

    def esc(v):
        return html.escape("" if v is None else str(v))

    reason_rows = "".join(
        f"<tr><td>{esc(k)}</td><td>{esc(v)}</td></tr>"
        for k, v in sorted(result["reason_counts"].items())
    )
    if not reason_rows:
        reason_rows = "<tr><td colspan='2'>无</td></tr>"

    audit_trs = []
    for r in result["audit_rows"]:
        cls = {"clean": "ok", "duplicate": "dup", "quarantine": "bad"}.get(
            r["disposition"], "dup"
        )
        audit_trs.append(
            "<tr class='{cls}'>"
            f"<td>{esc(r['source_row'])}</td>"
            f"<td>{esc(r['raw_order_id'])}</td>"
            f"<td>{esc(r['raw_date'])}</td>"
            f"<td>{esc(r['raw_amount'])}</td>"
            f"<td>{esc(r['raw_status'])}</td>"
            f"<td>{esc(r['order_id'])}</td>"
            f"<td>{esc(r['date'])}</td>"
            f"<td>{esc(r['amount'])}</td>"
            f"<td>{esc(r['status'])}</td>"
            f"<td>{esc(r['disposition'])}</td>"
            f"<td>{esc(r['reasons'])}</td>"
            f"<td>{esc(r['transformations'])}</td>"
            "</tr>".format(cls=cls)
        )
    audit_html = "".join(audit_trs)

    rules_html = ""
    if rules_text:
        rules_html = (
            "<section><h2>清洗规则（来自输入目录）</h2>"
            f"<p class='muted'>文件：{esc(rules_name)}</p>"
            f"<pre>{esc(rules_text)}</pre></section>"
        )

    return f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>D03 数据清洗质量报告</title>
<style>
  body {{ font-family: -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif; margin: 0; background: #f5f6f8; color: #1f2329; }}
  .wrap {{ max-width: 1200px; margin: 0 auto; padding: 24px; }}
  h1 {{ font-size: 22px; margin: 0 0 4px; }}
  h2 {{ font-size: 17px; margin: 28px 0 8px; border-left: 4px solid #2f6fed; padding-left: 8px; }}
  .muted {{ color: #6b7280; font-size: 12px; }}
  .cards {{ display: flex; gap: 16px; flex-wrap: wrap; margin-top: 16px; }}
  .card {{ background: #fff; border-radius: 10px; padding: 16px 20px; min-width: 120px; box-shadow: 0 1px 3px rgba(0,0,0,.06); }}
  .card .num {{ font-size: 28px; font-weight: 700; }}
  .card .label {{ color: #6b7280; font-size: 13px; }}
  .card.ok .num {{ color: #1a7f37; }}
  .card.bad .num {{ color: #d1242f; }}
  .card.dup .num {{ color: #9a6700; }}
  table {{ border-collapse: collapse; width: 100%; background: #fff; font-size: 13px; }}
  th, td {{ border: 1px solid #e5e7eb; padding: 6px 8px; text-align: left; vertical-align: top; }}
  th {{ background: #f0f3f8; position: sticky; top: 0; }}
  tr.ok td {{ background: #f0faf2; }}
  tr.dup td {{ background: #fff8e1; }}
  tr.bad td {{ background: #fdecec; }}
  pre {{ background: #fff; border: 1px solid #e5e7eb; border-radius: 8px; padding: 12px; white-space: pre-wrap; font-size: 13px; }}
  .table-scroll {{ overflow-x: auto; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,.06); }}
  footer {{ margin-top: 28px; color: #6b7280; font-size: 12px; }}
</style>
</head>
<body>
<div class="wrap">
  <h1>数据清洗质量报告 · D03</h1>
  <p class="muted">输入文件：{esc("、".join(input_files))}　|　由 cleaner.py 生成（确定性输出）</p>

  <div class="cards">
    <div class="card"><div class="num">{esc(counts['total'])}</div><div class="label">原始数据行</div></div>
    <div class="card ok"><div class="num">{esc(counts['clean'])}</div><div class="label">通过清洗 (clean)</div></div>
    <div class="card bad"><div class="num">{esc(counts['quarantine'])}</div><div class="label">隔离 (quarantine)</div></div>
    <div class="card dup"><div class="num">{esc(counts['duplicate'])}</div><div class="label">重复 (duplicate)</div></div>
  </div>

  {rules_html}

  <section>
    <h2>原因统计</h2>
    <table>
      <tr><th style="width:40%">原因类别</th><th>行数</th></tr>
      {reason_rows}
    </table>
  </section>

  <section>
    <h2>逐行审计（audit.csv）</h2>
    <div class="table-scroll">
    <table>
      <tr>
        <th>source_row</th>
        <th>raw_order_id</th><th>raw_date</th><th>raw_amount</th><th>raw_status</th>
        <th>order_id</th><th>date</th><th>amount</th><th>status</th>
        <th>disposition</th><th>reasons</th><th>transformations</th>
      </tr>
      {audit_html}
    </table>
    </div>
  </section>

  <footer>复现：<code>python3 cleaner.py --input-dir inputs --output-dir outputs</code>（同一输入多次运行输出内容一致）。</footer>
</div>
</body>
</html>
"""


def write_outputs(result, output_dir: Path, input_files, rules_name, rules_text):
    output_dir.mkdir(parents=True, exist_ok=True)

    _write_csv(
        output_dir / "clean.csv",
        COLUMNS,
        result["clean_rows"],
    )
    _write_csv(
        output_dir / "quarantine.csv",
        ["source_row", COL_ORDER_ID, COL_DATE, COL_AMOUNT, COL_STATUS, "reasons"],
        result["quarantine_rows"],
    )
    _write_csv(
        output_dir / "audit.csv",
        [
            "source_row",
            "raw_order_id",
            "raw_date",
            "raw_amount",
            "raw_status",
            COL_ORDER_ID,
            COL_DATE,
            COL_AMOUNT,
            COL_STATUS,
            "disposition",
            "reasons",
            "transformations",
        ],
        result["audit_rows"],
    )

    summary = {
        "input_files": input_files,
        "rules_file": rules_name or None,
        "total_data_rows": result["counts"]["total"],
        "clean": result["counts"]["clean"],
        "duplicate": result["counts"]["duplicate"],
        "quarantine": result["counts"]["quarantine"],
        "reason_counts": dict(sorted(result["reason_counts"].items())),
        "clean_order_ids": result["clean_order_ids"],
        "duplicate_source_rows": result["duplicate_source_rows"],
        "quarantine_source_rows": result["quarantine_source_rows"],
        "no_silent_row_loss": (
            result["counts"]["clean"]
            + result["counts"]["duplicate"]
            + result["counts"]["quarantine"]
            == result["counts"]["total"]
        ),
    }
    (output_dir / "summary.json").write_text(
        json.dumps(summary, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )

    (output_dir / "质量报告.html").write_text(
        render_html(result, input_files, rules_name, rules_text),
        encoding="utf-8",
    )
    return summary


# --------------------------------------------------------------------------- #
# 主流程。
# --------------------------------------------------------------------------- #
def run(input_dir: Path, output_dir: Path):
    input_dir = input_dir.resolve()
    output_dir = output_dir.resolve()

    if not input_dir.is_dir():
        raise CleaningError(f"输入目录不存在: {input_dir}")

    csv_files = sorted(
        [p for p in input_dir.iterdir() if p.is_file() and p.suffix.lower() == ".csv"]
    )
    if not csv_files:
        raise CleaningError(f"输入目录中没有 .csv 文件: {input_dir}")

    all_clean = []
    all_quarantine = []
    all_duplicate = []
    all_audit = []
    reason_counts = {}
    input_names = []

    for path in csv_files:
        _header, records = read_csv(path)
        result = clean_records(records)
        all_clean.extend(result["clean_rows"])
        all_quarantine.extend(result["quarantine_rows"])
        all_duplicate.extend(result["duplicate_rows"])
        all_audit.extend(result["audit_rows"])
        for k, v in result["reason_counts"].items():
            reason_counts[k] = reason_counts.get(k, 0) + v
        input_names.append(path.name)

    merged = {
        "clean_rows": all_clean,
        "quarantine_rows": all_quarantine,
        "duplicate_rows": all_duplicate,
        "audit_rows": all_audit,
        "reason_counts": reason_counts,
        "counts": {
            "total": len(all_audit),
            "clean": len(all_clean),
            "duplicate": len(all_duplicate),
            "quarantine": len(all_quarantine),
        },
        "clean_order_ids": [r[COL_ORDER_ID] for r in all_clean],
        "duplicate_source_rows": [r["source_row"] for r in all_duplicate],
        "quarantine_source_rows": [r["source_row"] for r in all_quarantine],
    }

    rules_name, rules_text = _load_rules(input_dir)
    summary = write_outputs(merged, output_dir, input_names, rules_name, rules_text)

    if not summary["no_silent_row_loss"]:
        raise CleaningError("行数不守恒：存在静默丢行，请检查实现")

    return summary


def build_parser():
    parser = argparse.ArgumentParser(
        description="可复用订单数据清洗器：读取输入目录 CSV，输出 clean/quarantine/audit/summary 与质量报告。"
    )
    parser.add_argument(
        "--input-dir",
        default=".",
        help="输入目录（含待清洗的 .csv，可选规则.md）。默认当前目录。",
    )
    parser.add_argument(
        "--output-dir",
        default="outputs",
        help="输出目录（生成 clean.csv 等）。默认 outputs/。",
    )
    return parser


def main(argv=None):
    args = build_parser().parse_args(argv)
    try:
        summary = run(Path(args.input_dir), Path(args.output_dir))
    except CleaningError as exc:
        print(f"[错误] {exc}", file=sys.stderr)
        return 2
    print(
        "清洗完成：总 {total} 行 = 通过 {clean} + 重复 {dup} + 隔离 {quarantine}".format(
            total=summary["total_data_rows"],
            clean=summary["clean"],
            dup=summary["duplicate"],
            quarantine=summary["quarantine"],
        )
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
