#!/usr/bin/env python3
"""Desensitize a JoySpace normal-doc content JSON in place.

Rules
-----
1. Replace absolute numeric quantities with XX, but keep:
   - Comparative deltas: 同比/环比/YOY/增速/涨幅/降幅/差距 and values containing pp / pct / %.
   - Numbers attached to ± sign (e.g. ``+2,070万`` / ``-0.001%``) — these read as deltas.
   - Numbers inside parentheses that look like deltas: ``(-0.5pp)`` / ``（+12.5%）``.
   - Month / date / time tokens (``9月`` / ``25M9`` / ``1230`` / ``2025年`` / ``Q3`` / ``H1``).
   - Domain proper nouns such as ``零售211``, ``98寸``, ``88分``, version numbers (``2.0``).
   - Phone-shaped order ids and explicit ``XXX`` placeholders.

2. Table desensitization: when a header row identifies columns as ``绝对值`` /
   ``单位`` / ``M5..M12`` / 单期金额 columns, blank the values in those columns
   for body rows while keeping 同比 / 环比 / YOY / 同比% columns intact.

3. Format preservation: this script edits ``text`` leaves and cell ``children``
   only; it never touches node ``type``, ``children`` structure, ``align``,
   ``backgroundColor``, ``width``, ``height``, table merge metadata, etc.
"""

from __future__ import annotations

from _monitor_autoload import finbox_autoload
finbox_autoload()

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any


# ---------------------------------------------------------------------------
# Tokenization
# ---------------------------------------------------------------------------

# Numeric tokens: integer / decimal / thousands-grouped, optionally with sign.
NUM_RE = re.compile(
    r"(?P<sign>[+\-±])?\s*(?P<num>\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?)"
)

DELTA_KEYWORDS = (
    "同比", "环比", "yoy", "YOY", "增速", "增长", "降幅", "涨幅", "升幅",
    "环增", "同减", "下降", "上涨", "环比+", "同比+",
    "增速", "差距", "波动", "改善", "恶化", "回落", "提升",
    "变动", "增幅", "降速", "增速率", "增长率",
)

# Unit suffixes that travel with the number (kept attached when blanking).
ABS_UNITS = (
    "亿", "万", "千", "百", "元", "方", "单", "人", "次", "分", "通", "台",
    "斤", "kg", "KG", "件", "M", "k", "K", "G", "MB", "GB", "%", "pp", "%",
)

# Proper-noun digit sequences that must be kept verbatim.
PROPER_NOUN_PATTERNS = [
    r"零售\s*211",
    r"\d+寸",
    r"\d+吋",
    r"\d{1,2}M\d{1,2}",         # 25M5, 26M6, 25M12 — year-month tag
    r"[A-Z]\d+",                # H1, Q3, M9, M12, KA
    r"\d{1,2}月",
    r"\d{1,2}日",
    r"\d+年",
    r"\d+月\d+日",
    r"工业\d+",
    r"4G", r"5G", r"3C", r"2C", r"2B",
    r"\d+分(?!钟)",             # 100分 / 88分 (score) — but NOT 100分钟 (duration)
    r"(?<![0-9.])\d+(?=[、．])", # heading / list marker like 1、一线现场...
    # MMDD date tokens followed by an action verb — e.g. "1030完成 / 1230上线
    # / 1017执行 / 1010增加 / 0815启动".
    r"(?<![0-9.])\d{4}(?=(?:完成|上线|执行|增加|启动|发布|部署|开始|结束|落地|交付|验收|实施|推进|确认|提报|提交|审核|改造|优化|切换|发版))",
]
PROPER_NOUN_RE = re.compile("|".join(PROPER_NOUN_PATTERNS))


# Pre-pass pattern: signed magnitude immediately followed by a paren-delta.
# Example: ``-0.002亿（-0.004亿）`` — outer is the absolute reading WITH a
# directional sign; paren chunk is the YoY/MoM delta. Blank only the outer
# (sign + value + unit), leaving the paren chunk for the normal pass to keep.
_SIGNED_ABS_PAREN_DELTA_RE = re.compile(
    r"(?P<outer>[+\-±]\s*(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?)"
    r"(?P<unit>亿元|亿|万元|万|千元|千|百元|百|"
    r"元/方|元/单|元/件|元/台|元/人|元/吨|元/包裹|元/票|元/订单|元/公斤|元/kg|元|"
    r"方/人/天|方/人天|方/人|方|"
    r"单/人/天|单/人|单|件|台|人|位|次|场|户|条|笔|个|公里|米|吨|包裹|票|订单|公斤|斤|kg|KG)?"
    r"(?=\s*[（(]\s*[+\-±]\s*\d)"
)


# ---------------------------------------------------------------------------
# Text-level desensitization
# ---------------------------------------------------------------------------

def _looks_like_delta(token: str) -> bool:
    """Numbers with sign, %, pp, or inside delta-parens are deltas — keep."""
    if any(k in token for k in ("pp", "pct", "%")):
        return True
    if token.lstrip().startswith(("+", "-", "±")):
        return True
    return False


def _is_proper_noun_span(text: str, start: int, end: int) -> bool:
    """Return True if the matched number sits inside a proper-noun token."""
    for pm in PROPER_NOUN_RE.finditer(text):
        if pm.start() <= start and pm.end() >= end:
            return True
    return False


_DELTA_PREFIX_KEYWORDS = (
    "同比",
    "环比",
    "YOY",
    "yoy",
    "Yoy",
    "增速",
    "增长率",
    "降幅",
    "涨幅",
    "升幅",
    "增幅",
    "降速",
    "增长",
    "下降",
    "上涨",
    "差距",
    "增收",
    "减少",
    "节降",
    "节约",
    "节省",
    "降本",
    "改善",
    "恶化",
)

_DELTA_PREFIX_WINDOW = 6

# Units that get absorbed and replaced with the value.
_ABSOLUTE_UNIT_RE = re.compile(
    r"(?:亿元|亿|万元|万|千元|千|百元|百|"
    r"元/方|元/单|元/件|元/台|元/人|元/吨|元/包裹|元/票|元/订单|元/公斤|元/kg|元|"
    r"方/人/天|方/人天|方/人|方|"
    r"单/人/天|单/人|单|件|台|人|位|分(?![+\-0-9])|"
    r"次|场|户|条|笔|个|分钟|小时|秒|公里|米|MB|GB|KB|TB|吨|包裹|票|订单|公斤|斤|kg|KG|"
    r"%|％)"
)

# Trailing tokens that signal the number itself is a delta (kept).
_DELTA_SUFFIX_RE = re.compile(r"(?:pp|pct|%|％)")


_PP_SUFFIX_RE = re.compile(r"pp|pct")


def _is_delta_number(segment: str, start: int, end: int, sign: str | None) -> tuple[bool, int]:
    """Return (keep_as_delta, suffix_len). suffix_len is how many extra
    characters belong to the delta marker (pp / pct) so the caller can skip
    them. Bare ``%`` is NOT a delta on its own — the user wants ``57.80%``
    blanked unless the value has a sign (``+12.5%``) or a delta keyword
    (``同比12.5%``).
    """
    # 1. Explicit sign means delta (e.g. +480人, -3.8pp, -2.7).
    if sign in ("+", "-", "±"):
        return True, 0

    # 2. Trailing pp / pct.
    after = segment[end : end + 4]
    m = _PP_SUFFIX_RE.match(after)
    if m:
        return True, len(m.group(0))

    # 3. Look back for delta keywords within a small window — e.g. "同比12.5%".
    look_start = max(0, start - _DELTA_PREFIX_WINDOW)
    before = segment[look_start:start]
    for kw in _DELTA_PREFIX_KEYWORDS:
        if kw in before:
            # If the kept number is followed by %, keep the % too.
            tail = segment[end : end + 2]
            if tail.startswith("%") or tail.startswith("％"):
                return True, 1
            return True, 0

    # 4. Proper-noun span — handled separately by the caller.
    return False, 0


def _segment_keeps_deltas(segment: str) -> str:
    """Replace absolute numbers in a single text segment with XX.

    Strategy: for every numeric run, decide *independently* whether it is a
    delta (has sign, %, pp, or follows 同比/环比/增速 within a small window)
    or an absolute value. Only absolute values are blanked.
    """
    if not segment or not any(ch.isdigit() for ch in segment):
        return segment

    result: list[str] = []
    cursor = 0
    for m in NUM_RE.finditer(segment):
        result.append(segment[cursor : m.start()])
        full = m.group(0)
        sign = m.group("sign")

        # Proper-noun spans always survive verbatim.
        if _is_proper_noun_span(segment, m.start(), m.end()):
            result.append(full)
            cursor = m.end()
            continue

        is_delta, suffix_len = _is_delta_number(segment, m.start(), m.end(), sign)
        if is_delta:
            result.append(full + segment[m.end() : m.end() + suffix_len])
            cursor = m.end() + suffix_len
            continue

        # Absorb a trailing unit so "0.7亿" → "XX亿" but "57.80%" → "XX"
        # (the % is consumed and dropped per the user's spec).
        unit_match = _ABSOLUTE_UNIT_RE.match(segment[m.end() :])
        unit = unit_match.group(0) if unit_match else ""
        keep_unit = unit if unit not in ("%", "％") else ""
        result.append("XX" + keep_unit)
        cursor = m.end() + len(unit)

    result.append(segment[cursor:])
    return "".join(result)


def _blank_signed_abs_with_paren_delta(text: str) -> str:
    """Pre-pass: ``-0.002亿（-0.004亿）`` → ``XX亿（-0.004亿）``.

    The outer signed magnitude reads as an absolute (its sign is just the
    direction of the absolute value, not a delta), while the paren chunk is
    the actual YoY/MoM delta and must survive. Keep the unit so the reader
    still sees magnitude scale (亿 / 万 / 单 / 次 …) without learning the
    number itself.
    """
    def repl(m: re.Match[str]) -> str:
        unit = m.group("unit") or ""
        return "XX" + unit

    return _SIGNED_ABS_PAREN_DELTA_RE.sub(repl, text)


def desensitize_text(text: str) -> str:
    if not text:
        return text
    text = _blank_signed_abs_with_paren_delta(text)
    return _segment_keeps_deltas(text)


# ---------------------------------------------------------------------------
# Table-level desensitization
# ---------------------------------------------------------------------------

ABSOLUTE_HEADER_TOKENS = {
    "绝对值",
    "原始值",
    "金额",
    "数值",
    "单位",
    "本期",
    "目标",
    "实际",
    "今年",
    "去年",
    "实绝对值",
    "本期绝对值",
    "上期绝对值",
    "件数",
    "单量",
}

DELTA_HEADER_TOKENS = {
    "同比", "环比", "yoy", "YOY", "增速", "增长", "降幅", "涨幅",
    "同比%", "环比%", "同比增速", "环比增速", "同比变动",
    "排名", "得分", "差距", "目标差", "差异", "占比", "rate", "%",
    "pp", "pct",
}

MONTH_HEADER_RE = re.compile(r"^\d*M\d+$|^\d+月$|^Q[1-4]$|^H[12]$")


def _cell_text(cell: dict[str, Any]) -> str:
    """Recursively collect plain text out of a JoySpace cell node."""

    def walk(n: Any) -> str:
        if n is None:
            return ""
        if isinstance(n, str):
            return n
        if isinstance(n, dict):
            text = n.get("text", "") or ""
            for child in n.get("children", []) or []:
                text += walk(child)
            return text
        return ""

    return walk(cell).strip()


def _classify_columns(header_cells: list[dict[str, Any]]) -> list[str]:
    """Return per-column kind: ``delta``, ``absolute``, or ``unknown``."""
    kinds: list[str] = []
    for cell in header_cells:
        text = _cell_text(cell)
        lt = text.lower()
        if not text:
            kinds.append("unknown")
            continue
        if any(tok.lower() in lt for tok in DELTA_HEADER_TOKENS):
            kinds.append("delta")
            continue
        if any(tok in text for tok in ABSOLUTE_HEADER_TOKENS) or MONTH_HEADER_RE.match(text):
            kinds.append("absolute")
            continue
        kinds.append("unknown")
    return kinds


def _blank_cell_inplace(cell: dict[str, Any]) -> None:
    """Replace all numeric content inside a cell with XX while keeping format.

    This is only called for cells in columns classified as ``absolute`` — the
    delta-column / delta-row guards in :func:`desensitize_table` already short
    -circuit before we get here. So even when the surface form looks like a
    delta (e.g. ``-34.5%`` for a profit rate, sitting under a ``绝对值``
    header), we trust the column classification and blank.
    """
    text = _cell_text(cell)
    if not text:
        return
    # Run text-level desensitize. If nothing changed, force-blank when the
    # cell is mostly numeric.
    new_text = desensitize_text(text)
    if new_text == text and re.search(r"\d", text):
        new_text = "XX"

    # Push the new text into the first text leaf; clear other text leaves.
    leaves: list[dict[str, Any]] = []

    def collect(node: Any) -> None:
        if isinstance(node, dict):
            if "text" in node:
                leaves.append(node)
            for child in node.get("children", []) or []:
                collect(child)

    for child in cell.get("children", []) or []:
        collect(child)

    if not leaves:
        cell["children"] = [{"text": new_text}]
        return
    leaves[0]["text"] = new_text
    for leaf in leaves[1:]:
        leaf["text"] = ""


_HEADER_KIND_PRIORITY = {"delta": 2, "absolute": 1, "unknown": 0}


def _row_looks_like_header(cells: list[dict[str, Any]]) -> bool:
    """A row is header-like only when every non-empty cell is either purely
    textual (no digits) or matches a month/period tag (``M5`` / ``Q3`` /
    ``9月`` / ``H1``).

    This keeps multi-tier headers like ``本期 / 同比 / 本期 / 同比`` and
    ``M5 / M5 / M6 / M6`` classified as headers, while body rows that mix
    Chinese labels with measurement digits (``5.47元/单（-6.7%）``) are NOT
    mistaken for headers.
    """
    if not cells:
        return False
    saw_label = False
    for c in cells:
        text = _cell_text(c)
        if not text:
            continue
        if any(ch.isdigit() for ch in text):
            # Allow month / period / year-month tags as header labels.
            if MONTH_HEADER_RE.match(text) or re.match(r"^\d{1,2}M\d{1,2}$", text):
                saw_label = True
                continue
            # Mixed text + digits → body cell.
            return False
        saw_label = True
    return saw_label


def _merge_column_kinds(base: list[str], extra: list[str]) -> list[str]:
    """Combine two per-column classifications. The deeper (later) tier is more
    specific than the broader (earlier) one — a category-group cell like
    ``增长`` / ``利润`` in row 0 tells us less about the actual column kind
    than a tier-2 cell like ``绝对值`` / ``同比`` sitting directly above the
    body values. So any non-``unknown`` signal in a deeper tier overrides
    whatever an earlier tier said for that column. Only when the deeper tier
    is ``unknown`` do we keep the earlier tier's kind.
    """
    out = list(base)
    for i, kind in enumerate(extra):
        if i >= len(out):
            out.append(kind)
            continue
        if kind != "unknown":
            out[i] = kind
    return out


def desensitize_table(table: dict[str, Any]) -> None:
    rows = [r for r in table.get("children", []) or [] if isinstance(r, dict)]
    if not rows:
        return

    # Walk through leading rows and treat each header-like row as a header
    # tier. Stop at the first body row (or after 3 header rows, whichever
    # comes first). Merge per-column kinds across all header tiers so a
    # ``同比`` mark living in row 1 is picked up even when row 0 is just a
    # month-group span.
    column_kinds: list[str] = []
    body_start = 0
    for i, row in enumerate(rows[:3]):
        cells = [c for c in row.get("children", []) or [] if isinstance(c, dict)]
        if not cells:
            body_start = i + 1
            continue
        if i == 0 or _row_looks_like_header(cells):
            tier_kinds = _classify_columns(cells)
            column_kinds = _merge_column_kinds(column_kinds, tier_kinds)
            body_start = i + 1
        else:
            break

    if not column_kinds:
        column_kinds = ["unknown"] * len(rows[0].get("children", []) or [])

    # If the row label / row-axis indicates delta (e.g. cell[0] text =
    # "件均成本同比" or "达成同比"), keep every value in that row.
    row_axis_label_re = re.compile(r"同比|环比|YOY|yoy|增速|增长率|降幅|涨幅|增幅")

    # A "compound" cell has the absolute reading AND a paren-delta in the same
    # text (e.g. ``5.47元/单（-6.7%）``). Always run the text rule on these so
    # the outer magnitude is blanked, even when the surrounding column / row
    # is otherwise classified as a delta.
    compound_cell_re = re.compile(r"\d.*?[（(]\s*[+\-±]\s*\d")

    for row in rows[body_start:]:
        cells = [c for c in row.get("children", []) or [] if isinstance(c, dict)]
        if not cells:
            continue

        # Use the first two cells as the row-label window (handles two-tier
        # row labels like ``件均成本同比 / 目标``).
        row_label = " ".join(_cell_text(c) for c in cells[:2])
        row_is_delta = bool(row_axis_label_re.search(row_label))

        for idx, cell in enumerate(cells):
            kind = column_kinds[idx] if idx < len(column_kinds) else "unknown"
            # 同比 / 环比 / YOY columns and rows are trusted verbatim — every
            # number inside is a delta by construction. Skip them BEFORE the
            # compound-cell check so cells like ``+12.5%（-0.5pp）`` in a
            # 同比 column stay intact.
            if kind == "delta":
                continue
            if row_is_delta and idx >= 1:
                continue
            cell_text_value = _cell_text(cell)
            is_compound = bool(compound_cell_re.search(cell_text_value))
            if is_compound:
                # Compound absolute (e.g. ``5.47元/单（-6.7%）``) in an
                # absolute / unknown column: run the text rule so the outer
                # magnitude is blanked while the paren delta survives.
                _walk_and_desensitize_text(cell)
                continue
            if kind == "absolute":
                _blank_cell_inplace(cell)
                continue
            # unknown column: still scrub numbers via text rule.
            _walk_and_desensitize_text(cell)


# ---------------------------------------------------------------------------
# Tree walk
# ---------------------------------------------------------------------------

def _walk_and_desensitize_text(node: Any) -> None:
    if isinstance(node, dict):
        if "text" in node and isinstance(node.get("text"), str):
            node["text"] = desensitize_text(node["text"])
        children = node.get("children")
        if isinstance(children, list):
            for child in children:
                _walk_and_desensitize_text(child)
    elif isinstance(node, list):
        for item in node:
            _walk_and_desensitize_text(item)


def desensitize_content(content: list[Any]) -> list[Any]:
    """Top-level entry. Returns the same list, mutated in place."""
    for node in content:
        if not isinstance(node, dict):
            continue
        node_type = node.get("type")
        if node_type == "table":
            desensitize_table(node)
        else:
            _walk_and_desensitize_text(node)
    return content


# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------

def _load_envelope(path: Path) -> tuple[dict[str, Any], list[Any]]:
    raw = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(raw, dict) and isinstance(raw.get("data"), dict) and "content" in raw["data"]:
        return raw, raw["data"]["content"]
    if isinstance(raw, dict) and isinstance(raw.get("content"), list):
        return raw, raw["content"]
    if isinstance(raw, list):
        return {"content": raw}, raw
    raise SystemExit("Unsupported JSON shape; expected JoySpace envelope or array.")


def main() -> int:
    parser = argparse.ArgumentParser(description="Desensitize a JoySpace doc JSON in place")
    parser.add_argument("--input", required=True, help="Path to JoySpace content JSON")
    parser.add_argument("--output", required=True, help="Output JSON path")
    parser.add_argument("--emit-content-only", action="store_true",
                        help="Write only the content array (suitable for --content-json-file)")
    parser.add_argument("--report", help="Optional desensitize report path (JSON)")
    args = parser.parse_args()

    envelope, content = _load_envelope(Path(args.input))
    before = json.dumps(content, ensure_ascii=False)
    desensitize_content(content)
    after = json.dumps(content, ensure_ascii=False)

    out_path = Path(args.output)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    if args.emit_content_only:
        out_path.write_text(json.dumps(content, ensure_ascii=False, indent=2), encoding="utf-8")
    else:
        out_path.write_text(json.dumps(envelope, ensure_ascii=False, indent=2), encoding="utf-8")

    if args.report:
        Path(args.report).write_text(json.dumps({
            "inputBytes": len(before.encode("utf-8")),
            "outputBytes": len(after.encode("utf-8")),
            "changed": before != after,
        }, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"status": "success", "output": str(out_path), "changed": before != after}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except SystemExit:
        raise
    except Exception as exc:  # pragma: no cover
        print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)
