"""
D02 报价版本对比 —— 核心计算模块（纯标准库，可独立单测）

职责：
  1. 读取两版报价 CSV（只读，不改原文件）
  2. 逐行校验，遇到重复 SKU / 币种不一致 / 税口径不一致等异常时登记问题，绝不静默合并
  3. 以 SKU 为匹配键，逐项标注：新增 / 移除 / 数量变化 / 单价变化 / 数量+单价变化 / 无变化
  4. 汇总两版金额与总差额，并对"数量与价格同时变化"的旧品按统一口径做影响分解：
        数量影响 = (新量 - 旧量) * 旧价
        价格影响 = 新量 * (新价 - 旧价)
  5. 输出结构化的 DiffResult，供 xlsx / html / md 三个渲染器使用

金额口径：金额 = 数量 * 单价，四舍五入（ROUND_HALF_UP）保留 2 位小数。
"""
from __future__ import annotations

import csv
import hashlib
import io
import unicodedata
from dataclasses import dataclass, field
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
from pathlib import Path
from typing import Any, Iterable

CENT = Decimal("0.01")
ZERO = Decimal("0")

# 变化类型（也是差异页的筛选项）
TYPE_NEW = "新增"
TYPE_REMOVED = "移除"
TYPE_QTY = "数量变化"
TYPE_PRICE = "单价变化"
TYPE_BOTH = "数量+单价变化"
TYPE_SAME = "无变化"
TYPE_PENDING = "待确认"

CHANGE_TYPES = [TYPE_NEW, TYPE_REMOVED, TYPE_QTY, TYPE_PRICE, TYPE_BOTH, TYPE_SAME, TYPE_PENDING]

# 状态
STATUS_OK = "ok"          # 计入合计
STATUS_PENDING = "pending"  # 异常，列出待确认，不计入合计

LEVEL_HIGH = "高"
LEVEL_MID = "中"
LEVEL_LOW = "低"

HEADER_ALIASES: dict[str, set[str]] = {
    "sku": {"sku", "编码", "商品编码", "货号", "料号", "sku编码"},
    "name": {"名称", "商品名称", "品名", "name", "product", "产品名称"},
    "qty": {"数量", "qty", "quantity", "件数"},
    "price": {"单价", "price", "unitprice", "unit_price", "价格"},
    "currency": {"币种", "货币", "currency", "ccy"},
    "tax": {"税口径", "税", "tax", "taxbasis", "tax_basis", "含税口径"},
}

CURRENCY_ALIASES = {
    "人民币": "CNY", "rmb": "CNY", "元": "CNY", "cny": "CNY", "¥": "CNY", "￥": "CNY",
    "美元": "USD", "美金": "USD", "usd": "USD", "$": "USD",
    "欧元": "EUR", "eur": "EUR", "€": "EUR",
    "港币": "HKD", "港元": "HKD", "hkd": "HKD",
    "日元": "JPY", "jpy": "JPY",
    "英镑": "GBP", "gbp": "GBP",
}

CURRENCY_SYMBOLS = "¥￥$€£"


# ----------------------------------------------------------------------------- 基础工具
def norm_text(value: Any) -> str:
    """NFKC 归一 + 去首尾空白（含全角空格）。不做大小写折叠，避免把不同 SKU 静默合并。"""
    if value is None:
        return ""
    return unicodedata.normalize("NFKC", str(value)).strip()


def header_key(value: str) -> str:
    s = norm_text(value).lower()
    for ch in (" ", "_", "-", "\u3000", ":"):
        s = s.replace(ch, "")
    return s


def quantize_money(value: Decimal) -> Decimal:
    return value.quantize(CENT, rounding=ROUND_HALF_UP)


def parse_decimal(raw: Any, *, allow_negative: bool = True) -> tuple[Decimal | None, str | None]:
    """解析数字：容忍千分位逗号、空格、货币符号、末尾'元'。返回 (值, 错误信息)。"""
    text = norm_text(raw)
    if text == "":
        return None, "为空"
    cleaned = text
    for ch in CURRENCY_SYMBOLS:
        cleaned = cleaned.replace(ch, "")
    for ch in (" ", ",", "\u3000", "_"):
        cleaned = cleaned.replace(ch, "")
    if cleaned.endswith("元"):
        cleaned = cleaned[:-1]
    if cleaned.startswith("+"):
        cleaned = cleaned[1:]
    if cleaned == "":
        return None, f"无法识别为数字：{text!r}"
    # 全角负号/小数点已在 NFKC 中归一
    try:
        value = Decimal(cleaned)
    except InvalidOperation:
        return None, f"不是合法数字：{text!r}"
    if not value.is_finite():
        return None, f"不是有限数字：{text!r}"
    if not allow_negative and value < 0:
        return None, f"不允许负数：{text!r}"
    return value, None


def norm_currency(raw: Any) -> tuple[str, str | None]:
    """返回 (标准化币种, 错误)。未知币种保留大写原文但标记错误，避免猜测。"""
    text = norm_text(raw)
    if text == "":
        return "", "币种为空"
    key = header_key(text.replace(" ", ""))
    if key in CURRENCY_ALIASES:
        return CURRENCY_ALIASES[key], None
    upper = text.upper()
    if upper in CURRENCY_ALIASES:
        return CURRENCY_ALIASES[upper], None
    if len(upper) == 3 and upper.isalpha():
        return upper, None  # 形如 XXX 的三字母代码，先按原样登记
    return upper, f"未识别币种：{text!r}"


def file_sha256(path: Path) -> str:
    return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def decode_bytes(data: bytes) -> tuple[str, str]:
    """按 utf-8-sig → utf-8 → gb18030 依次尝试，返回 (文本, 实际编码)。"""
    for enc in ("utf-8-sig", "utf-8", "gb18030"):
        try:
            return data.decode(enc), enc
        except UnicodeDecodeError:
            continue
    return data.decode("utf-8", errors="replace"), "utf-8(replace)"


# ----------------------------------------------------------------------------- 数据模型
@dataclass
class Issue:
    seq: int
    level: str
    kind: str
    detail: str
    handling: str
    sku: str = ""
    version: str = ""
    rows: tuple[int, ...] = ()
    amount: Decimal | None = None
    currency: str = ""

    def as_dict(self) -> dict[str, Any]:
        return {
            "序号": self.seq, "级别": self.level, "问题类型": self.kind, "SKU": self.sku,
            "版本": self.version, "文件行号": "、".join(str(r) for r in self.rows),
            "问题描述": self.detail, "处理方式": self.handling,
            "待确认金额": self.amount, "币种": self.currency,
        }


@dataclass
class QuoteRow:
    version: str
    row_no: int
    sku: str
    name: str
    qty: Decimal | None
    price: Decimal | None
    currency: str
    tax: str
    raw: dict[str, str] = field(default_factory=dict)
    errors: list[str] = field(default_factory=list)

    @property
    def amount(self) -> Decimal | None:
        if self.qty is None or self.price is None:
            return None
        return quantize_money(self.qty * self.price)

    @property
    def usable(self) -> bool:
        return self.qty is not None and self.price is not None and self.currency != "" and not self.errors


@dataclass
class FileInfo:
    label: str
    path: str
    encoding: str
    sha256: str
    row_count: int
    valid_rows: int


@dataclass
class DiffRow:
    sku: str
    change_type: str
    status: str
    name_old: str = ""
    name_new: str = ""
    qty_old: Decimal | None = None
    qty_new: Decimal | None = None
    price_old: Decimal | None = None
    price_new: Decimal | None = None
    amount_old: Decimal | None = None
    amount_new: Decimal | None = None
    amount_diff: Decimal | None = None
    qty_impact: Decimal | None = None
    price_impact: Decimal | None = None
    rounding_gap: Decimal | None = None
    currency: str = ""
    tax_old: str = ""
    tax_new: str = ""
    rows_old: tuple[int, ...] = ()
    rows_new: tuple[int, ...] = ()
    note: str = ""

    @property
    def name(self) -> str:
        return self.name_new or self.name_old

    @property
    def qty_delta(self) -> Decimal | None:
        if self.qty_old is None or self.qty_new is None:
            return None
        return self.qty_new - self.qty_old

    @property
    def price_delta(self) -> Decimal | None:
        if self.price_old is None or self.price_new is None:
            return None
        return self.price_new - self.price_old

    @property
    def counted(self) -> bool:
        return self.status == STATUS_OK

    def as_dict(self) -> dict[str, Any]:
        """列顺序即 xlsx / html 的列顺序。"""
        return {
            "SKU": self.sku,
            "名称": self.name,
            "变化类型": self.change_type,
            "旧数量": self.qty_old,
            "新数量": self.qty_new,
            "数量变动": self.qty_delta,
            "旧单价": self.price_old,
            "新单价": self.price_new,
            "单价变动": self.price_delta,
            "旧金额": self.amount_old,
            "新金额": self.amount_new,
            "金额差额": self.amount_diff,
            "数量影响": self.qty_impact,
            "价格影响": self.price_impact,
            "分解尾差": self.rounding_gap,
            "币种": self.currency,
            "税口径_旧": self.tax_old,
            "税口径_新": self.tax_new,
            "计入合计": "是" if self.counted else "否",
            "备注": self.note,
        }


DIFF_COLUMNS = [
    "SKU", "名称", "变化类型", "旧数量", "新数量", "数量变动", "旧单价", "新单价", "单价变动",
    "旧金额", "新金额", "金额差额", "数量影响", "价格影响", "分解尾差", "币种",
    "税口径_旧", "税口径_新", "计入合计", "备注",
]


@dataclass
class DiffResult:
    v1_label: str
    v2_label: str
    files: list[FileInfo]
    rows: list[DiffRow]
    issues: list[Issue]
    totals: dict[str, Any]
    generated_at: str
    source_dir: str = ""

    # ---- 便捷视图
    @property
    def changed_rows(self) -> list[DiffRow]:
        return [r for r in self.rows if r.change_type not in (TYPE_SAME,)]

    def type_counts(self) -> dict[str, int]:
        counts = {t: 0 for t in CHANGE_TYPES}
        for r in self.rows:
            counts[r.change_type] = counts.get(r.change_type, 0) + 1
        return counts

    def type_amounts(self) -> dict[str, Decimal | None]:
        out: dict[str, Decimal | None] = {}
        for t in CHANGE_TYPES:
            subset = [r for r in self.rows if r.change_type == t and r.amount_diff is not None]
            out[t] = sum((r.amount_diff for r in subset), ZERO) if subset else None
        return out


# ----------------------------------------------------------------------------- 读取与校验
def find_columns(header: list[str]) -> dict[str, int]:
    keys = [header_key(h) for h in header]
    mapping: dict[str, int] = {}
    for field_name, aliases in HEADER_ALIASES.items():
        norm_aliases = {header_key(a) for a in aliases}
        for idx, key in enumerate(keys):
            if key in norm_aliases:
                mapping[field_name] = idx
                break
    return mapping


def read_quote_csv(path: str | Path, label: str, issues: list[Issue], seq_start: int = 0) -> tuple[list[QuoteRow], FileInfo, int]:
    """读取并校验单个版本。返回 (行, 文件信息, 下一个问题序号)。只读，不修改源文件。"""
    p = Path(path)
    data = p.read_bytes()
    text, encoding = decode_bytes(data)

    parsed: list[list[str]] = list(csv.reader(io.StringIO(text)))
    # 记录每行的物理行号
    line_nos: list[int] = []
    reader = csv.reader(io.StringIO(text))
    for _ in reader:
        line_nos.append(reader.line_num)

    header_idx = None
    for i, row in enumerate(parsed):
        if any(norm_text(c) for c in row):
            header_idx = i
            break
    if header_idx is None:
        raise ValueError(f"{p} 是空文件，找不到表头")

    header = parsed[header_idx]
    cols = find_columns(header)
    # SKU 是匹配键，必须有；数量/单价是金额基础，必须有。名称/币种/税口径强烈建议有。
    required = {"sku": "SKU", "qty": "数量", "price": "单价"}
    missing = [cn for key, cn in required.items() if key not in cols]
    if missing:
        raise ValueError(f"{p} 缺少必需列：{'、'.join(missing)}；实际表头：{header}")

    if "currency" not in cols:
        issues.append(Issue(seq=len(issues) + 1, level=LEVEL_HIGH, kind="缺少币种列",
                            detail="文件没有币种列，无法判断跨币种可比性",
                            handling="整版金额不做合计，仅列明细；请补充币种后重跑", version=label))
    if "tax" not in cols:
        issues.append(Issue(seq=len(issues) + 1, level=LEVEL_LOW, kind="缺少税口径列",
                            detail="文件没有税口径列，视为同口径比较（含税/不含税未知）",
                            handling="在复核说明中标注该限制", version=label))

    rows: list[QuoteRow] = []
    for offset, raw_row in enumerate(parsed[header_idx + 1:], start=0):
        row_no = line_nos[header_idx + 1 + offset] if header_idx + 1 + offset < len(line_nos) else header_idx + 2 + offset
        if not any(norm_text(c) for c in raw_row):
            continue  # 跳过空行

        def cell(key: str) -> str:
            idx = cols.get(key)
            if idx is None or idx >= len(raw_row):
                return ""
            return raw_row[idx]

        row_errors: list[str] = []
        sku = norm_text(cell("sku"))
        if sku == "":
            row_errors.append("SKU 为空")
            issues.append(Issue(seq=len(issues) + 1, level=LEVEL_HIGH, kind="SKU 缺失",
                                detail=f"第 {row_no} 行 SKU 为空，无法参与匹配",
                                handling="该行剔除，不计入合计", version=label, rows=(row_no,)))

        qty, qty_err = parse_decimal(cell("qty"), allow_negative=False)
        if qty_err:
            row_errors.append(f"数量{qty_err}")
            issues.append(Issue(seq=len(issues) + 1, level=LEVEL_HIGH, kind="数量无效",
                                detail=f"第 {row_no} 行（SKU={sku or '空'}）数量{qty_err}",
                                handling="该行金额不计入合计", sku=sku, version=label, rows=(row_no,)))
        price, price_err = parse_decimal(cell("price"), allow_negative=False)
        if price_err:
            row_errors.append(f"单价{price_err}")
            issues.append(Issue(seq=len(issues) + 1, level=LEVEL_HIGH, kind="单价无效",
                                detail=f"第 {row_no} 行（SKU={sku or '空'}）单价{price_err}",
                                handling="该行金额不计入合计", sku=sku, version=label, rows=(row_no,)))

        currency, cur_err = norm_currency(cell("currency")) if "currency" in cols else ("", "缺少币种列")
        if cur_err and "currency" in cols:
            row_errors.append(cur_err)
            issues.append(Issue(seq=len(issues) + 1, level=LEVEL_HIGH, kind="币种异常",
                                detail=f"第 {row_no} 行（SKU={sku or '空'}）{cur_err}",
                                handling="该行不计入合计，待确认币种", sku=sku, version=label, rows=(row_no,)))

        if qty is not None and qty == 0:
            issues.append(Issue(seq=len(issues) + 1, level=LEVEL_LOW, kind="数量为 0",
                                detail=f"第 {row_no} 行（SKU={sku or '空'}）数量为 0，金额为 0",
                                handling="保留该行，金额按 0 计", sku=sku, version=label, rows=(row_no,)))

        rows.append(QuoteRow(version=label, row_no=row_no, sku=sku, name=norm_text(cell("name")),
                             qty=qty, price=price, currency=currency,
                             tax=norm_text(cell("tax")),
                             raw={k: norm_text(v) for k, v in zip(header, raw_row)},
                             errors=row_errors))

    info = FileInfo(label=label, path=str(p), encoding=encoding, sha256=file_sha256(p),
                    row_count=len(rows), valid_rows=sum(1 for r in rows if r.usable))
    return rows, info, len(issues)


def detect_duplicates(rows: Iterable[QuoteRow], version: str, issues: list[Issue]) -> dict[str, list[QuoteRow]]:
    """按 SKU 分组；同版重复即登记问题，并返回该组（绝不合并取值）。

    完全重复（数量/单价/币种/税口径都相同）→ 中；数值冲突 → 高。
    """
    groups: dict[str, list[QuoteRow]] = {}
    for r in rows:
        if r.sku:
            groups.setdefault(r.sku, []).append(r)

    dups: dict[str, list[QuoteRow]] = {}
    for sku, group in groups.items():
        if len(group) < 2:
            continue
        dups[sku] = group
        sig = {(g.qty, g.price, g.currency, g.tax) for g in group}
        line_str = "、".join(str(g.row_no) for g in group)
        if len(sig) == 1:
            total = sum((g.amount or ZERO for g in group), ZERO)
            issues.append(Issue(
                seq=len(issues) + 1, level=LEVEL_MID, kind="重复 SKU（完全重复）",
                detail=f"{version} 版 SKU={sku} 出现 {len(group)} 次（第 {line_str} 行），各字段完全一致",
                handling="不合并取值；该 SKU 标记待确认，两版对应金额均不计入合计",
                sku=sku, version=version, rows=tuple(g.row_no for g in group),
                amount=total, currency=group[0].currency))
        else:
            detail = "；".join(f"第 {g.row_no} 行 数量={g.qty} 单价={g.price} 币种={g.currency or '空'}" for g in group)
            total = sum((g.amount or ZERO for g in group), ZERO)
            issues.append(Issue(
                seq=len(issues) + 1, level=LEVEL_HIGH, kind="重复 SKU（数值冲突）",
                detail=f"{version} 版 SKU={sku} 出现 {len(group)} 次且取值冲突：{detail}",
                handling="不合并、不取首末行；该 SKU 标记待确认，请人工确认应以哪一行为准",
                sku=sku, version=version, rows=tuple(g.row_no for g in group),
                amount=total, currency=group[0].currency))
    return dups


# ----------------------------------------------------------------------------- 差异计算
def build_diff(rows_v1: list[QuoteRow], rows_v2: list[QuoteRow],
               dups1: dict[str, list[QuoteRow]], dups2: dict[str, list[QuoteRow]],
               issues: list[Issue]) -> list[DiffRow]:
    old_map = {r.sku: r for r in rows_v1 if r.sku and r.sku not in dups1}
    new_map = {r.sku: r for r in rows_v2 if r.sku and r.sku not in dups2}

    # 待确认 SKU：重复项 + 行级校验失败项，一律不参与计算
    pending: dict[str, tuple[list[QuoteRow], list[QuoteRow]]] = {}
    for sku, group in dups1.items():
        pending.setdefault(sku, ([], []))[0].extend(group)
    for sku, group in dups2.items():
        pending.setdefault(sku, ([], []))[1].extend(group)
    for r in rows_v1:
        if r.errors and r.sku:
            pending.setdefault(r.sku, ([], []))[0].append(r)
            old_map.pop(r.sku, None)
    for r in rows_v2:
        if r.errors and r.sku:
            pending.setdefault(r.sku, ([], []))[1].append(r)
            new_map.pop(r.sku, None)

    all_keys = sorted(set(old_map) | set(new_map) | set(pending), key=_sku_sort_key)
    diff_rows: list[DiffRow] = []

    for sku in all_keys:
        old = old_map.get(sku)
        new = new_map.get(sku)
        p_old, p_new = pending.get(sku, ([], []))

        if p_old or p_new:
            diff_rows.append(_pending_row(sku, p_old, p_new, old, new))
            continue

        assert old is not None or new is not None
        if old is not None and new is not None:
            # 可比性检查：币种、税口径
            problems: list[str] = []
            if old.currency != new.currency:
                problems.append(f"币种不一致：旧版 {old.currency} / 新版 {new.currency}")
            if old.tax != new.tax and (old.tax or new.tax):
                problems.append(f"税口径不一致：旧版 {old.tax or '空'} / 新版 {new.tax or '空'}")
            if problems:
                issue_kind = "币种不一致" if old.currency != new.currency else "税口径不一致"
                issues.append(Issue(
                    seq=len(issues) + 1,
                    level=LEVEL_HIGH if issue_kind == "币种不一致" else LEVEL_MID,
                    kind=issue_kind,
                    detail=f"SKU={sku}（{new.name or old.name}）{'；'.join(problems)}",
                    handling="两版金额不可直接相减；差异列为待确认，不计入合计差额",
                    sku=sku, version=f"{old.version} → {new.version}",
                    rows=(old.row_no, new.row_no),
                    amount=None, currency=f"{old.currency}/{new.currency}"))
                diff_rows.append(DiffRow(
                    sku=sku, change_type=TYPE_PENDING, status=STATUS_PENDING,
                    name_old=old.name, name_new=new.name,
                    qty_old=old.qty, qty_new=new.qty,
                    price_old=old.price, price_new=new.price,
                    amount_old=old.amount, amount_new=new.amount,
                    currency=f"{old.currency}→{new.currency}",
                    tax_old=old.tax, tax_new=new.tax,
                    rows_old=(old.row_no,), rows_new=(new.row_no,),
                    note="；".join(problems) + "；未计入合计差额"))
                continue

            qty_d = new.qty - old.qty
            price_d = new.price - old.price
            if qty_d == 0 and price_d == 0:
                ctype = TYPE_SAME
            elif qty_d != 0 and price_d == 0:
                ctype = TYPE_QTY
            elif qty_d == 0 and price_d != 0:
                ctype = TYPE_PRICE
            else:
                ctype = TYPE_BOTH

            amt_old, amt_new = old.amount, new.amount
            amt_diff = quantize_money(amt_new - amt_old)
            qty_imp = quantize_money(qty_d * old.price)
            price_imp = quantize_money(new.qty * price_d)
            gap = quantize_money(amt_diff - qty_imp - price_imp)

            notes: list[str] = []
            if old.name != new.name:
                notes.append(f"名称由「{old.name}」改为「{new.name}」")
            if ctype == TYPE_BOTH:
                notes.append("数量与价格同时变化，已按 数量影响=(新量-旧量)×旧价、价格影响=新量×(新价-旧价) 分解")
            if gap != 0:
                notes.append("分解尾差来自分项四舍五入")

            diff_rows.append(DiffRow(
                sku=sku, change_type=ctype, status=STATUS_OK,
                name_old=old.name, name_new=new.name,
                qty_old=old.qty, qty_new=new.qty,
                price_old=old.price, price_new=new.price,
                amount_old=amt_old, amount_new=amt_new, amount_diff=amt_diff,
                qty_impact=qty_imp, price_impact=price_imp, rounding_gap=gap,
                currency=old.currency, tax_old=old.tax, tax_new=new.tax,
                rows_old=(old.row_no,), rows_new=(new.row_no,),
                note="；".join(notes)))
        elif old is not None:
            diff_rows.append(DiffRow(
                sku=sku, change_type=TYPE_REMOVED, status=STATUS_OK,
                name_old=old.name, name_new="",
                qty_old=old.qty, price_old=old.price,
                amount_old=old.amount, amount_new=ZERO,
                amount_diff=quantize_money(-old.amount),
                currency=old.currency, tax_old=old.tax, rows_old=(old.row_no,),
                note="仅旧版存在，按整行移除处理（新金额记 0）"))
        else:
            assert new is not None
            diff_rows.append(DiffRow(
                sku=sku, change_type=TYPE_NEW, status=STATUS_OK,
                name_old="", name_new=new.name,
                qty_new=new.qty, price_new=new.price,
                amount_old=ZERO, amount_new=new.amount,
                amount_diff=new.amount,
                currency=new.currency, tax_new=new.tax, rows_new=(new.row_no,),
                note="仅新版存在，按整行新增处理（旧金额记 0）"))
    return diff_rows


def _plain(value: Decimal | None) -> str:
    """4 → "4"，50.5 → "50.5"（用于候选值留痕，不补零）。"""
    if value is None:
        return "—"
    s = format(value, "f")
    if "." in s:
        s = s.rstrip("0").rstrip(".")
    return s or "0"


def _pending_row(sku: str, p_old: list[QuoteRow], p_new: list[QuoteRow],
                 old: QuoteRow | None, new: QuoteRow | None) -> DiffRow:
    """待确认行：重复 SKU 时不挑选任何代表值，只把候选值写进备注留痕。"""
    dup = len(p_old) > 1 or len(p_new) > 1
    o = None if dup else (p_old[0] if p_old else old)
    n = None if dup else (p_new[0] if p_new else new)

    parts: list[str] = []
    if dup:
        parts.append(f"重复 SKU：旧版 {len(p_old)} 行 / 新版 {len(p_new)} 行，未合并、未取代表值")
        for label, group in (("旧版", p_old), ("新版", p_new)):
            if group:
                cand = "；".join(
                    f"第{r.row_no}行 {_plain(r.qty)}×{_plain(r.price)}={fnum_core(r.amount)}" for r in group)
                parts.append(f"{label}候选：{cand}")
    for r in p_old + p_new:
        if r.errors:
            parts.append(f"第 {r.row_no} 行校验失败（{'、'.join(r.errors)}）")

    row = DiffRow(
        sku=sku, change_type=TYPE_PENDING, status=STATUS_PENDING,
        name_old=(o.name if o else (p_old[0].name if p_old else (new.name if new else ""))),
        name_new=(n.name if n else (p_new[0].name if p_new else "")),
        qty_old=o.qty if o else None, qty_new=n.qty if n else None,
        price_old=o.price if o else None, price_new=n.price if n else None,
        amount_old=o.amount if o else None,
        amount_new=n.amount if n else None,
        currency=(o.currency if o else (p_old[0].currency if p_old else (n.currency if n else ""))),
        tax_old=(o.tax if o else (p_old[0].tax if p_old else "")),
        tax_new=(n.tax if n else (p_new[0].tax if p_new else "")),
        rows_old=tuple(r.row_no for r in p_old), rows_new=tuple(r.row_no for r in p_new),
        note="；".join(dict.fromkeys(parts)) or "存在异常，待人工确认")
    return row


def fnum_core(value: Decimal | None) -> str:
    if value is None:
        return "—"
    return f"{value:,.2f}"


def _sku_sort_key(sku: str) -> tuple[int, Any]:
    digits = "".join(ch for ch in sku if ch.isdigit())
    head = "".join(ch for ch in sku if not ch.isdigit())
    if digits and head:
        return (0, (head, int(digits), sku))
    return (1, (sku,))


# ----------------------------------------------------------------------------- 汇总
def summarize(diff_rows: list[DiffRow], issues: list[Issue]) -> dict[str, Any]:
    """合计只统计 status==ok 的行；待确认行单独列示，避免把异常数据混进合计。"""
    ok = [r for r in diff_rows if r.counted and r.amount_diff is not None]

    old_total = quantize_money(sum((r.amount_old for r in ok if r.amount_old is not None), ZERO))
    new_total = quantize_money(sum((r.amount_new for r in ok if r.amount_new is not None), ZERO))
    total_diff = quantize_money(new_total - old_total)

    per_currency: dict[str, dict[str, Decimal]] = {}
    for r in ok:
        cur = r.currency or "未标注"
        bucket = per_currency.setdefault(cur, {"old": ZERO, "new": ZERO, "diff": ZERO})
        bucket["old"] += r.amount_old or ZERO
        bucket["new"] += r.amount_new or ZERO
        bucket["diff"] += r.amount_diff or ZERO
    per_currency = {k: {kk: quantize_money(vv) for kk, vv in v.items()} for k, v in per_currency.items()}

    by_type: dict[str, dict[str, Any]] = {}
    for t in CHANGE_TYPES:
        subset = [r for r in ok if r.change_type == t]
        by_type[t] = {
            "count": len(subset),
            "diff": quantize_money(sum((r.amount_diff for r in subset), ZERO)),
            "qty_impact": quantize_money(sum((r.qty_impact for r in subset if r.qty_impact is not None), ZERO)),
            "price_impact": quantize_money(sum((r.price_impact for r in subset if r.price_impact is not None), ZERO)),
        }

    pending_rows = [r for r in diff_rows if not r.counted]
    pending_amounts: dict[str, Decimal] = {}
    for r in pending_rows:
        if r.amount_old is not None:
            cur = (r.currency.split("→")[0] if "→" in r.currency else r.currency) or "未标注"
            pending_amounts[cur] = pending_amounts.get(cur, ZERO) + r.amount_old
        if r.amount_new is not None:
            cur = (r.currency.split("→")[-1] if "→" in r.currency else r.currency) or "未标注"
            pending_amounts[cur] = pending_amounts.get(cur, ZERO) + r.amount_new
    pending_amounts = {k: quantize_money(v) for k, v in pending_amounts.items()}

    # 校验恒等式
    checks: list[dict[str, Any]] = []
    sum_type_diff = quantize_money(sum((by_type[t]["diff"] for t in CHANGE_TYPES), ZERO))
    checks.append({
        "项": "各变化类型金额差额之和 = 总差额",
        "左": sum_type_diff, "右": total_diff, "通过": _eq(sum_type_diff, total_diff),
        "说明": "按类型分组不重不漏覆盖全部计入合计的行",
    })
    sum_cur_diff = quantize_money(sum((v["diff"] for v in per_currency.values()), ZERO))
    multi_currency = len(per_currency) > 1
    checks.append({
        "项": "各币种差额之和 = 总差额",
        "左": sum_cur_diff, "右": total_diff, "通过": _eq(sum_cur_diff, total_diff),
        "说明": ("存在多币种，总额仅为算术示意，结论须分币种看" if multi_currency
                 else "单一币种，可直接相加"),
    })
    # 影响分解只对「两版同名」的 SKU 成立：新增/移除是整行进出，不做量价拆分
    matched = [r for r in ok if r.qty_impact is not None and r.price_impact is not None]
    qty_imp = quantize_money(sum((r.qty_impact for r in matched), ZERO))
    price_imp = quantize_money(sum((r.price_impact for r in matched), ZERO))
    gap = quantize_money(sum((r.rounding_gap for r in matched), ZERO))
    matched_diff = quantize_money(sum((r.amount_diff for r in matched), ZERO))
    new_diff = quantize_money(sum((r.amount_diff for r in ok if r.change_type == TYPE_NEW), ZERO))
    removed_diff = quantize_money(sum((r.amount_diff for r in ok if r.change_type == TYPE_REMOVED), ZERO))
    both_diff = quantize_money(sum((r.amount_diff for r in ok if r.change_type == TYPE_BOTH), ZERO))
    both_imp = quantize_money(sum(((r.qty_impact or ZERO) + (r.price_impact or ZERO) + (r.rounding_gap or ZERO)
                                   for r in ok if r.change_type == TYPE_BOTH), ZERO))
    checks.append({
        "项": "数量影响 + 价格影响 + 尾差 = 两版同名 SKU 差额合计",
        "左": quantize_money(qty_imp + price_imp + gap), "右": matched_diff,
        "通过": _eq(quantize_money(qty_imp + price_imp + gap), matched_diff),
        "说明": f"数量影响={qty_imp}，价格影响={price_imp}，尾差={gap}；范围仅限两版同名 SKU",
    })
    checks.append({
        "项": "同时变化类：数量影响 + 价格影响 + 尾差 = 该类差额",
        "左": both_imp, "右": both_diff,
        "通过": _eq(both_imp, both_diff),
        "说明": "数量影响=(新量-旧量)×旧价，价格影响=新量×(新价-旧价)",
    })
    checks.append({
        "项": "两版同名差额 + 新增差额 + 移除差额 = 总差额",
        "左": quantize_money(matched_diff + new_diff + removed_diff), "右": total_diff,
        "通过": _eq(quantize_money(matched_diff + new_diff + removed_diff), total_diff),
        "说明": f"同名={matched_diff}，新增={new_diff}，移除={removed_diff}",
    })
    checks.append({
        "项": "旧版合计 + 总差额 = 新版合计",
        "左": quantize_money(old_total + total_diff), "右": new_total,
        "通过": _eq(quantize_money(old_total + total_diff), new_total),
        "说明": "总差额定义即新版合计 - 旧版合计",
    })

    return {
        "old_total": old_total, "new_total": new_total, "total_diff": total_diff,
        "per_currency": per_currency, "by_type": by_type, "multi_currency": multi_currency,
        "qty_impact_total": qty_imp, "price_impact_total": price_imp, "rounding_gap_total": gap,
        "matched_diff": matched_diff, "new_diff": new_diff, "removed_diff": removed_diff,
        "matched_rows": len(matched),
        "pending_rows": len(pending_rows), "pending_amounts": pending_amounts,
        "issue_count": len(issues),
        "issue_levels": {lv: sum(1 for i in issues if i.level == lv) for lv in (LEVEL_HIGH, LEVEL_MID, LEVEL_LOW)},
        "checks": checks,
        "counted_rows": len(ok),
    }


def _eq(a: Decimal, b: Decimal) -> bool:
    return abs(a - b) < Decimal("0.005")


# ----------------------------------------------------------------------------- 顶层入口
def run(v1_path: str | Path, v2_path: str | Path, generated_at: str,
        v1_label: str = "v1", v2_label: str = "v2") -> DiffResult:
    issues: list[Issue] = []
    rows1, info1, _ = read_quote_csv(v1_path, v1_label, issues)
    rows2, info2, _ = read_quote_csv(v2_path, v2_label, issues, seq_start=len(issues))

    dups1 = detect_duplicates(rows1, v1_label, issues)
    dups2 = detect_duplicates(rows2, v2_label, issues)

    # 同一文件内多币种：登记问题，合计按币种分列
    for rows, label in ((rows1, v1_label), (rows2, v2_label)):
        currencies = sorted({r.currency for r in rows if r.currency})
        if len(currencies) > 1:
            issues.append(Issue(
                seq=len(issues) + 1, level=LEVEL_MID, kind="同版多币种",
                detail=f"{label} 版含多种币种：{'、'.join(currencies)}，不存在汇率，不能跨币种汇总",
                handling="合计按币种分列展示，不给出跨币种单一总额", version=label,
                currency="、".join(currencies)))

    diff_rows = build_diff(rows1, rows2, dups1, dups2, issues)
    totals = summarize(diff_rows, issues)
    for i, issue in enumerate(issues, start=1):
        issue.seq = i
    totals["issue_count"] = len(issues)

    return DiffResult(v1_label=v1_label, v2_label=v2_label, files=[info1, info2],
                      rows=diff_rows, issues=issues, totals=totals,
                      generated_at=generated_at,
                      source_dir=str(Path(v1_path).resolve().parent))
