#!/usr/bin/env python3
"""Replay redacted order or contact events in an isolated local reference ledger."""

from __future__ import annotations

import argparse
import csv
import json
import re
from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass
from decimal import Decimal, DecimalException, InvalidOperation
from html import escape
from pathlib import Path
from typing import Any, Protocol, Union, cast
from urllib.parse import parse_qsl


class SampleError(ValueError):
    """An input cannot be interpreted without guessing its schema."""


RecordValue = Union[str, int, bool, Decimal]


@dataclass(frozen=True)
class Event:
    event_id: str
    sale_id: str
    kind: str
    amount: Decimal | None
    currency: str | None
    value: RecordValue | None = None


@dataclass(frozen=True)
class SaleState:
    amount: Decimal
    currency: str
    refunded: bool = False


@dataclass(frozen=True)
class RefundState:
    sale_id: str
    amount: Decimal
    currency: str


class ReplayTarget(Protocol):
    """Read/write contract for an isolated test adapter."""

    def write(self, event: Event) -> None: ...
    def backfill(self, sales: Iterable[Event]) -> None: ...
    def sales(self) -> list[tuple[str, SaleState]]: ...
    def refunds(self) -> list[tuple[str, RefundState]]: ...


@dataclass(frozen=True)
class ContactState:
    value: RecordValue


@dataclass(frozen=True)
class UpdateState:
    contact_id: str
    value: RecordValue


class ContactReplayTarget(Protocol):
    """Read/write contract for an isolated contact test adapter."""

    def write(self, event: Event) -> None: ...
    def backfill(self, contacts: Iterable[Event]) -> None: ...
    def contacts(self) -> list[tuple[str, ContactState]]: ...
    def updates(self) -> list[tuple[str, UpdateState]]: ...


class ReferenceLedger:
    """In-memory replay target with keyed primary records and independent amendments."""

    def __init__(self) -> None:
        self._sales: dict[str, Event] = {}
        self._refunds: dict[str, Event] = {}
        self._contacts: dict[str, Event] = {}
        self._updates: dict[str, Event] = {}

    def write(self, event: Event) -> None:
        entries = {
            "sale": self._sales,
            "refund": self._refunds,
            "create": self._contacts,
            "update": self._updates,
        }[event.kind]
        key = event.sale_id if event.kind in ("sale", "create") else event.event_id
        entries.setdefault(key, event)

    def backfill(self, records: Iterable[Event]) -> None:
        for event in records:
            self.write(event)

    def sales(self) -> list[tuple[str, SaleState]]:
        refunded_ids = {event.sale_id for event in self._refunds.values()}
        return [
            expected_sale(event, sale_id in refunded_ids)
            for sale_id, event in self._sales.items()
        ]

    def refunds(self) -> list[tuple[str, RefundState]]:
        return [expected_refund(event) for event in self._refunds.values()]

    def contacts(self) -> list[tuple[str, ContactState]]:
        latest_updates = {event.sale_id: event for event in self._updates.values()}
        return [
            (contact_id, ContactState(require_value(latest_updates.get(contact_id, event))))
            for contact_id, event in self._contacts.items()
        ]

    def updates(self) -> list[tuple[str, UpdateState]]:
        return [expected_update(event) for event in self._updates.values()]


@dataclass(frozen=True)
class Check:
    title: str
    status: str
    evidence: str
    ids: tuple[str, ...] = ()


DEFAULT_FIELDS = {
    "sale_id", "event_id", "refund_id", "refund_sale_id", "kind",
    "amount", "refund_amount", "currency", "value", "status",
}
EVENT_KINDS = ("sale", "refund", "create", "update")
DEFAULT_COLLECTION_KEYS = ("events", "records", "sales", "rows", "items", "data")


def value_at(row: Mapping[str, Any], field: str) -> Any:
    if field in row:
        return row[field]
    value: Any = row
    for part in field.split("."):
        if not isinstance(value, Mapping):
            return None
        value = value.get(part)
    return value


def load_sample(path: Path) -> Any:
    text = path.read_text(encoding="utf-8-sig")
    suffix = path.suffix.lower()
    if suffix == ".csv":
        reader = csv.DictReader(text.splitlines(keepends=True), strict=True)
        if not reader.fieldnames or len(reader.fieldnames) != len(set(reader.fieldnames)):
            raise SampleError("CSV is missing a unique header.")
        rows = list(reader)
        if any(None in row for row in rows):
            raise SampleError("A CSV row has more values than the header.")
        return rows
    if suffix in {".jsonl", ".ndjson"}:
        return [json.loads(line, parse_float=Decimal) for line in text.splitlines() if line.strip()]
    if suffix in {".form", ".urlencoded", ".webhook", ".txt"} and not text.lstrip().startswith(("{", "[")):
        pairs = parse_qsl(text.strip(), keep_blank_values=True, strict_parsing=True)
        if len(pairs) != len(dict(pairs)):
            raise SampleError("The form sample contains duplicate field names.")
        return dict(pairs)
    return json.loads(text, parse_float=Decimal)


def rows_for(data: Any, options: Mapping[str, Any]) -> list[Mapping[str, Any]]:
    path = options.get("records_path")
    if path:
        if not isinstance(path, str) or not isinstance(data, Mapping):
            raise SampleError("records_path must name an object field.")
        data = value_at(data, path)
        if data is None:
            raise SampleError("The configured records_path is missing.")
    elif isinstance(data, Mapping):
        nested = [data[key] for key in DEFAULT_COLLECTION_KEYS if isinstance(data.get(key), list)]
        if len(nested) > 1:
            raise SampleError("Several record arrays were found. Set records_path.")
        if nested:
            data = nested[0]
    if isinstance(data, Mapping):
        data = [data]
    if not isinstance(data, list) or any(not isinstance(row, Mapping) for row in data):
        raise SampleError("Expected a record object or an array of record objects.")
    return data


def first_value(*values: Any) -> Any:
    return next((value for value in values if value is not None and value != ""), None)


def text_id(value: Any) -> str:
    if not isinstance(value, (str, int)) or isinstance(value, bool):
        return ""
    return str(value).strip()


def money(
    row: Mapping[str, Any], fields: Mapping[str, str], options: Mapping[str, Any],
    kind: str, allowed_currencies: frozenset[str] | None,
) -> tuple[Decimal, str]:
    raw_currency = (value_at(row, fields["currency"]) if "currency" in fields
                    else first_value(row.get("amount_currency"), row.get("currency")))
    currency = first_value(raw_currency, options.get("default_currency"))
    scale = options.get("amount_scale", 0)
    mapped_amount = (fields.get("refund_amount") if kind == "refund" else None) or fields.get("amount")
    if mapped_amount:
        amount = value_at(row, mapped_amount)
    else:
        candidates = []
        if kind == "refund":
            candidates.extend([
                (row.get("refund_amount_usd"), "USD", 0),
                (row.get("refund_amount_cents"), "USD", 2),
                (row.get("refund_amount"), currency, scale),
            ])
        candidates.extend([
            (row.get("amount_usd"), "USD", 0),
            (row.get("price"), "USD", 2),
            (row.get("price_cents"), "USD", 2),
            (row.get("amount"), currency, scale),
        ])
        amount, currency, scale = next(
            (candidate for candidate in candidates if candidate[0] not in (None, "")),
            (None, currency, scale),
        )
    if type(scale) is not int or not 0 <= scale <= 9:
        raise SampleError("amount_scale must be an integer between 0 and 9.")
    if not isinstance(currency, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9]{2,7}", currency.strip()):
        raise SampleError("A settlement currency code such as USD, GBP or USDC is required.")
    currency = currency.strip().upper()
    if allowed_currencies is not None and currency.casefold() not in allowed_currencies:
        raise SampleError("This preset does not cover the settlement currency or amount scale.")
    try:
        parsed = Decimal(str(amount))
        if (not parsed.is_finite() or (parsed < 0 and kind == "sale")
                or len(parsed.as_tuple().digits) > 28 or abs(parsed.adjusted()) > 28):
            raise InvalidOperation
        if scale and parsed != parsed.to_integral_value():
            raise InvalidOperation
        parsed = parsed.copy_abs().scaleb(-scale)
    except DecimalException as error:
        raise SampleError("Invalid decimal amount or unit. Sale amounts must be nonnegative.") from error
    return parsed, currency


def allowlist(options: Mapping[str, Any], key: str) -> frozenset[str] | None:
    if key not in options:
        return None
    values = options[key]
    if not isinstance(values, list) or not values or any(not isinstance(v, str) or not v.strip() for v in values):
        raise SampleError(f"{key} must contain at least one nonempty string.")
    return frozenset(value.strip().casefold() for value in values)


def normalize(data: Any, options: Mapping[str, Any]) -> list[Event]:
    fields = options.get("fields", {})
    event_types = options.get("event_types", {})
    if not isinstance(fields, Mapping) or any(
        key not in DEFAULT_FIELDS or not isinstance(field, str) or not field.strip() for key, field in fields.items()
    ):
        raise SampleError("fields must map supported names to CSV columns or JSON paths.")
    if not isinstance(event_types, Mapping) or any(v not in EVENT_KINDS for v in event_types.values()):
        raise SampleError("event_types must map source labels to sale, refund, create, or update.")
    allowed_currencies = allowlist(options, "allowed_currencies")
    allowed_statuses = allowlist(options, "allowed_statuses")
    if ("status" in fields) != (allowed_statuses is not None):
        raise SampleError("Configure fields.status and allowed_statuses together.")
    events: list[Event] = []
    by_event_id: dict[str, Event] = {}
    for number, row in enumerate(rows_for(data, options), start=1):
        event_id = text_id(value_at(row, fields.get("event_id", "event_id")))
        refund_id = text_id(value_at(row, fields.get("refund_id", "refund_id")))
        raw_kind = value_at(row, fields.get("kind", "event_type"))
        kind = str(raw_kind or ("refund" if refund_id else "sale")).strip().lower()
        kind = event_types.get(kind, kind)
        id_field = "refund_sale_id" if kind == "refund" and "refund_sale_id" in fields else "sale_id"
        sale_id = text_id(value_at(row, fields.get(id_field, "sale_id")))
        try:
            if not sale_id:
                raise SampleError(f"Missing {id_field}. Check the field mapping.")
            if fields.get("kind") and raw_kind in (None, ""):
                raise SampleError("Missing configured event type.")
            if kind not in EVENT_KINDS:
                raise SampleError("Unknown event type. Configure event_types.")
            if allowed_statuses is not None:
                status = text_id(value_at(row, fields["status"])).casefold()
                if status not in allowed_statuses:
                    raise SampleError("This preset requires a confirmed successful event status.")
            if "event_id" in fields and not event_id:
                raise SampleError("Missing configured event ID. Supply a captured event ID for each row.")
            if kind == "sale" and not event_id:
                event_id = sale_id
            if kind == "refund" and not event_id:
                event_id = refund_id
            if not event_id:
                raise SampleError("Refund and contact events require their own event ID.")
            if kind in ("sale", "refund"):
                amount, currency = money(row, fields, options, kind, allowed_currencies)
                event = Event(event_id, sale_id, kind, amount, currency)
            else:
                value = value_at(row, fields.get("value", "value"))
                if (not isinstance(value, (str, int, bool, Decimal))
                        or (isinstance(value, str) and not value.strip())
                        or (isinstance(value, Decimal) and not value.is_finite())):
                    raise SampleError("A contact event requires a nonempty scalar value for readback.")
                event = Event(event_id, sale_id, kind, None, None, value)
            if event_id in by_event_id and by_event_id[event_id] != event:
                raise SampleError("The same event ID is associated with different data.")
        except SampleError as error:
            raise SampleError(f"Record {number}. {error}") from error
        by_event_id[event_id] = event
        events.append(event)
    return events


CHECKS = ("正常写入", "同 ID 重放", "退款乱序", "漏单补回")
CHECKS_EN = ("Normal write", "Same-ID replay", "Out-of-order refund", "Missed-event backfill")


def translated(lang: str, zh: str, en: str) -> str:
    return en if lang == "en" else zh


def check_titles(lang: str, contact: bool = False) -> tuple[str, ...]:
    titles = CHECKS_EN if lang == "en" else CHECKS
    if not contact:
        return titles
    return (*titles[:2], translated(lang, "更新乱序", "Out-of-order update"), titles[3])


def require_money(event: Event) -> tuple[Decimal, str]:
    if event.amount is None or event.currency is None:
        raise SampleError("Monetary event missing its amount or currency.")
    return event.amount, event.currency


def require_value(event: Event) -> RecordValue:
    if event.value is None:
        raise SampleError("Contact event missing its tracked value.")
    return event.value


def expected_sale(event: Event, refunded: bool = False) -> tuple[str, SaleState]:
    return event.sale_id, SaleState(*require_money(event), refunded)


def expected_refund(event: Event) -> tuple[str, RefundState]:
    return event.event_id, RefundState(event.sale_id, *require_money(event))


def expected_update(event: Event) -> tuple[str, UpdateState]:
    return event.event_id, UpdateState(event.sale_id, require_value(event))


def run_scenario(title: str, ids: tuple[str, ...], action: Callable[[], tuple[bool, str]], lang: str = "zh") -> Check:
    try:
        passed, evidence = action()
    except Exception as error:
        kind = type(error).__name__
        evidence = translated(lang, f"执行异常（{kind}）", f"Replay encountered an execution error ({kind}).")
        return Check(title, "FAIL", evidence, ids)
    return Check(title, "PASS" if passed else "FAIL", evidence, ids)


def replay_checks(
    events: list[Event],
    snapshot: list[Event] | None = None,
    target_factory: Callable[[], ReplayTarget | ContactReplayTarget] = ReferenceLedger,
    *,
    lang: str = "zh",
) -> list[Check]:
    families = {
        event.kind in ("create", "update")
        for event in [*events, *(snapshot or [])]
    }
    if len(families) > 1:
        evidence = translated(lang, "请分开回放订单与联系人样本。", "Replay order and contact samples separately.")
        return [Check(title, "BLOCKED", evidence) for title in check_titles(lang)]
    contact = True in families
    titles = check_titles(lang, contact)
    primary_kind, change_kind = ("create", "update") if contact else ("sale", "refund")
    primary = {event.sale_id: event for event in events if event.kind == primary_kind}
    source = {event.sale_id: event for event in (snapshot if snapshot is not None else events)
              if event.kind == primary_kind}
    first = next(iter(primary.values()), None)

    def read_rows(target: ReplayTarget | ContactReplayTarget) -> list[tuple[str, SaleState | ContactState]]:
        if contact:
            return list(cast(ContactReplayTarget, target).contacts())
        return list(cast(ReplayTarget, target).sales())

    def read_changes(target: ReplayTarget | ContactReplayTarget) -> list[tuple[str, RefundState | UpdateState]]:
        if contact:
            return list(cast(ContactReplayTarget, target).updates())
        return list(cast(ReplayTarget, target).refunds())

    def expected_row(event: Event, change: Event | None = None) -> tuple[str, SaleState | ContactState]:
        if contact:
            return event.sale_id, ContactState(require_value(change or event))
        return expected_sale(event, refunded=change is not None)

    checks: list[Check] = []
    if first is None:
        evidence = (
            translated(lang, "缺少联系人创建事件。", "Provide a contact creation event with an event ID and tracked value.")
            if contact else
            translated(lang, "缺少销售事件或销售导出行。", "Provide a sale event or a sale export row.")
        )
        checks.extend(Check(title, "BLOCKED", evidence) for title in titles[:2])
    else:
        def write(replays: int) -> tuple[bool, str]:
            target = target_factory()
            for _ in range(replays):
                target.write(first)
            actual = read_rows(target)
            ok = actual == [expected_row(first)] and not read_changes(target)
            match = "一致" if ok else "未全部匹配"
            if contact:
                evidence = translated(
                    lang,
                    f"读回 {len(actual)} 条联系人记录。联系人 ID 与字段值{match}。",
                    f"Read {len(actual)} contact row(s). Expected one row with the original contact ID and value.",
                )
            else:
                evidence = translated(
                    lang,
                    f"读回 {len(actual)} 条销售。订单 ID、金额、币种及无退款状态{match}。",
                    f"Read {len(actual)} sale row(s). Expected one with the original ID, amount, currency, and no refund.",
                )
            return ok, evidence

        checks.append(run_scenario(titles[0], (first.event_id,), lambda: write(1), lang))
        checks.append(run_scenario(titles[1], (first.event_id,), lambda: write(2), lang))

    pairable = {**source, **primary}
    changes = (event for event in events if event.kind == change_kind and event.sale_id in pairable)
    change = next((
        event for event in changes
        if (
            event.value != pairable[event.sale_id].value if contact
            else event.currency == pairable[event.sale_id].currency
        )
    ), None)
    if change is None:
        evidence = (
            translated(lang, "需同一联系人的创建事件和字段值不同的更新事件。", "Provide creation and changed update events for the same contact.")
            if contact else
            translated(lang, "缺少同一订单的销售与退款样本。", "Provide a sale and refund for the same order and settlement currency.")
        )
        checks.append(Check(titles[2], "BLOCKED", evidence))
    else:
        linked_primary = pairable[change.sale_id]

        def change_first() -> tuple[bool, str]:
            target = target_factory()
            target.write(change)
            early_rows = read_rows(target)
            target.write(linked_primary)
            rows_readback, changes_readback = read_rows(target), read_changes(target)
            target.write(change)
            expected = expected_update(change) if contact else expected_refund(change)
            ok = (
                not early_rows
                and rows_readback == [expected_row(linked_primary, change)]
                and changes_readback == [expected]
                and read_rows(target) == rows_readback
                and read_changes(target) == changes_readback
            )
            result = "正确" if ok else "未全部匹配"
            if contact:
                evidence = translated(
                    lang,
                    f"先更新后创建并再重放更新。读回 {len(rows_readback)} 条联系人记录、{len(changes_readback)} 条更新，关联及字段值{result}。",
                    f"Sent the update before creation and read back {len(rows_readback)} contact row(s) and {len(changes_readback)} update(s) before replay. Expected one updated contact and one update.",
                )
            else:
                evidence = translated(
                    lang,
                    f"先退款后销售并再重放退款。读回 {len(rows_readback)} 条销售、{len(changes_readback)} 条退款，关联及原金额{result}。",
                    f"Sent the refund before the sale and read back {len(rows_readback)} sale row(s) and {len(changes_readback)} refund(s) before replay. Expected both linked once with the original sale amount.",
                )
            return ok, evidence

        checks.append(run_scenario(titles[2], (change.event_id, linked_primary.event_id), change_first, lang))

    present = next((event for event in source.values() if event.sale_id in primary), None)
    present = present or next(iter(source.values()), None)
    remaining = [event for event in source.values() if event != present]
    omitted = next((event for event in remaining if event.sale_id not in primary), None)
    omitted = omitted or next(iter(remaining), None)
    if present is None or omitted is None:
        evidence = (
            translated(lang, "需至少两个不同联系人 ID，才能模拟保留一条并补回另一条。", "Provide two distinct contact IDs so one can be omitted and recovered.")
            if contact else
            translated(lang, "需至少两个不同销售 ID，才能模拟保留一笔并补回另一笔。", "Provide two distinct sale IDs so one can be omitted and recovered.")
        )
        checks.append(Check(titles[3], "BLOCKED", evidence))
    else:
        def backfill() -> tuple[bool, str]:
            target = target_factory()
            target.write(primary.get(present.sale_id, present))
            baseline = read_rows(target)
            source_pair = (present, omitted)
            target.backfill(source_pair)
            result = read_rows(target)
            target.backfill(source_pair)
            replayed = read_rows(target)
            expected = dict(map(expected_row, source_pair))
            ok = (baseline == [expected_row(present)] and len(result) == len(replayed) == 2
                  and dict(result) == dict(replayed) == expected and not read_changes(target))
            outcome = "验证通过" if ok else "未全部匹配"
            noun = "联系人记录" if contact else "销售"
            evidence = translated(
                lang,
                f"先故意漏写一笔，再按源快照补回并复跑。读回 {len(result)} 条{noun}，缺项及防重{outcome}。",
                f"Omitted one record, restored it from the source snapshot, and repeated reconciliation. Read {len(result)} row(s) after backfill and {len(replayed)} on rerun, expecting two both times.",
            )
            return ok, evidence

        checks.append(run_scenario(titles[3], (present.event_id, omitted.event_id), backfill, lang))
    return checks


def report_heading(lang: str) -> str:
    return translated(lang, "交易入表验收报告", "Workflow acceptance report")


def report_scope(lang: str, source: str) -> str:
    return translated(
        lang,
        f"范围：{source}｜本地参考账本的隔离回放。生产端写入与线上连接不在本次验收范围内。",
        f"Scope · {source}. Isolated replay in a local reference ledger. Live writes and connections require verification in an authorized test environment.",
    )


def report_counts(checks: list[Check], lang: str) -> str:
    prefix = translated(lang, "结果：", "Results · ")
    return prefix + " / ".join(
        f"{status} {sum(check.status == status for check in checks)}" for status in ("PASS", "FAIL", "BLOCKED")
    )


def report_columns(lang: str) -> tuple[str, ...]:
    return ("Check", "Result", "Event IDs", "Observed Evidence") if lang == "en" else ("验收项", "结果", "事件 ID", "观察证据")


def report_cells(check: Check) -> tuple[str, ...]:
    ids = ", ".join(re.sub(r"[\x00-\x1f\x7f]+", " ", event_id) for event_id in check.ids)
    return check.title, check.status, ids or "—", check.evidence


def markdown_cell(text: str) -> str:
    text = re.sub(r"[\x00-\x1f\x7f]+", " ", text)
    text = re.sub(r"([\\\[\]()])", r"\\\1", text)
    return escape(text, quote=False).replace("|", "&#124;").replace("`", "&#96;")


def render_report(checks: list[Check], source: str, lang: str = "zh") -> str:
    lines = [
        f"# {report_heading(lang)}",
        "",
        report_scope(lang, source),
        "",
        report_counts(checks, lang),
        "",
        f"| {' | '.join(report_columns(lang))} |",
        "| --- | --- | --- | --- |",
    ]
    for check in checks:
        lines.append(f"| {' | '.join(map(markdown_cell, report_cells(check)))} |")
    return "\n".join(lines) + "\n"


def render_html_report(checks: list[Check], source: str, lang: str = "zh") -> str:
    heading = escape(report_heading(lang))
    headers = "".join(f'<th scope="col">{escape(column)}</th>' for column in report_columns(lang))
    rows = []
    for check in checks:
        title, status, ids, evidence = (escape(value) for value in report_cells(check))
        rows.append(f'<tr><th scope="row">{title}</th><td><strong>{status}</strong></td><td>{ids}</td><td>{evidence}</td></tr>')
    return f"""<!doctype html>
<html lang="{escape(lang)}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<title>{heading}</title>
<style>
@page {{ margin: 15mm; }}
body {{ margin: 32px auto; padding: 0 16px; max-width: 880px; color: #17232c; font: 15px/1.5 system-ui, sans-serif; }}
h1 {{ margin: 0 0 12px; font-size: 26px; line-height: 1.2; }}
p {{ margin: 0 0 12px; }}
table {{ width: 100%; border-collapse: collapse; }}
th, td {{ padding: 10px 8px; border: 1px solid #83909a; vertical-align: top; text-align: left; overflow-wrap: anywhere; }}
thead th {{ background: #e5ebef; }}
tbody th {{ font-weight: 600; }}
tr {{ break-inside: avoid; }}
@media print {{ body {{ margin: 0; padding: 0; font-size: 10pt; }} h1 {{ font-size: 17pt; }} th, td {{ padding: 6px; }} }}
</style>
</head>
<body>
<main>
<h1>{heading}</h1>
<p>{escape(report_scope(lang, source))}</p>
<p><strong>{escape(report_counts(checks, lang))}</strong></p>
<table>
<thead><tr>{headers}</tr></thead>
<tbody>{"".join(rows)}</tbody>
</table>
</main>
</body>
</html>
"""


DEMO = [
    {"event_id": "REFUND-101", "sale_id": "SALE-101", "event_type": "refund", "amount": "2.45", "currency": "GBP"},
    {"event_id": "EVENT-101", "sale_id": "SALE-101", "event_type": "sale", "amount": "19.99", "currency": "GBP"},
    {"event_id": "EVENT-102", "sale_id": "SALE-102", "event_type": "sale", "amount": "32.50", "currency": "EUR"},
]


def load_options(path: Path | None) -> Mapping[str, Any]:
    if path is None:
        return {}
    options = json.loads(path.read_text(encoding="utf-8-sig"))
    if not isinstance(options, dict):
        raise SampleError("The mapping file must be a JSON object.")
    return options


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    sources = parser.add_mutually_exclusive_group(required=True)
    sources.add_argument("--input", type=Path, help="CSV, JSON, JSONL or saved webhook body")
    sources.add_argument("--demo", action="store_true", help="Run with synthetic example events")
    parser.add_argument("--mapping", type=Path, help="JSON field mapping for the primary sample")
    parser.add_argument("--snapshot", type=Path, help="Optional independent source-of-truth sales or contacts export")
    parser.add_argument("--snapshot-mapping", type=Path, help="Mapping for an export with different columns")
    parser.add_argument("--out", type=Path, help="Write the Markdown report to this file, or use stdout")
    parser.add_argument("--lang", choices=("en", "zh"), default="zh", help="Language for both report formats")
    parser.add_argument("--html", type=Path, help="Also write a standalone printable HTML report")
    args = parser.parse_args(argv)
    lang = args.lang
    if args.out and args.html and args.out.resolve() == args.html.resolve():
        parser.error("--out and --html must use different report paths.")

    source = (
        translated(lang, "合成样本", "Synthetic fixtures")
        if args.demo else translated(lang, "客户提供的样本", "Provided sample")
    )
    try:
        options = load_options(args.mapping)
        events = normalize(DEMO if args.demo else load_sample(args.input), options)
    except (OSError, ValueError, csv.Error) as error:
        kind = type(error).__name__
        evidence = str(error) if isinstance(error, SampleError) else translated(
            lang, f"主样本或映射无法读取（{kind}）。", f"Could not read the sample or mapping ({kind})."
        )
        checks = [Check(title, "BLOCKED", evidence) for title in check_titles(lang)]
    else:
        snapshot = None
        snapshot_error = None
        if args.snapshot is not None:
            try:
                snapshot_options = load_options(args.snapshot_mapping) if args.snapshot_mapping else options
                snapshot = normalize(load_sample(args.snapshot), snapshot_options)
                source += translated(lang, "和独立源快照", " and independent source snapshot")
            except (OSError, ValueError, csv.Error) as error:
                snapshot = []
                kind = type(error).__name__
                snapshot_error = str(error) if isinstance(error, SampleError) else translated(
                    lang, f"源快照无法读取（{kind}）。", f"Could not read the source snapshot ({kind})."
                )
        else:
            noun = "联系人记录" if any(event.kind in ("create", "update") for event in events) else "销售"
            source += translated(
                lang, f"，从同批{noun}构造漏单场景", " with the backfill scenario simulated from the same sample"
            )
        checks = replay_checks(events, snapshot, lang=lang)
        if snapshot_error:
            checks[-1] = Check(checks[-1].title, "BLOCKED", snapshot_error)
    report = render_report(checks, source, lang)
    if args.out:
        args.out.write_text(report, encoding="utf-8")
    else:
        print(report, end="")
    if args.html:
        args.html.write_text(render_html_report(checks, source, lang), encoding="utf-8")
    if any(check.status == "FAIL" for check in checks):
        return 1
    return 2 if any(check.status == "BLOCKED" for check in checks) else 0


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