#!/usr/bin/env python3
"""
Tanramisu Offline Local CSV Privacy Sanitizer (Mode 2 — Zero-Egress CLI)

- Zero third-party dependencies (Python 3.8+ standard library only)
- Zero networking imports (no socket / urllib / http — auditable in 30 seconds)
- Strips PII columns (CN/EN buyer name, phone, address, email, ID/bank card, WeChat/QQ)
- Redacts stray phone numbers, emails, ID cards, and bank card numbers inside kept columns
- Runs an automatic post-clean privacy gate check matching Tanramisu's server-side Mode 2 Gate

Usage:
    python local_sanitizer.py input_orders.csv [output_orders_sanitized.csv]
"""

from __future__ import annotations

import csv
import io
import pathlib
import re
import sys

PII_HEADER_PATTERNS = [
    re.compile(r"(姓名|买家|收件人|收货人|联系|手机|电话|地址|身份证|证件|邮箱|微信|qq|旺旺|昵称|银行卡)", re.I),
    re.compile(
        r"\b(name|buyer|customer_name|recipient|phone|mobile|tel|telephone|address|street|email|e-mail|ssn|id_card|passport|iban|bank_account)\b",
        re.I,
    ),
]

CELL_RULES = [
    ("cn_mobile", re.compile(r"(?<!\d)1[3-9]\d{9}(?!\d)")),
    ("email", re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")),
    ("cn_id_card", re.compile(r"(?<!\d)[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx](?!\d)")),
    ("bank_card", re.compile(r"(?<!\d)(?:62\d{14,17}|4\d{15}|5[1-5]\d{14})(?!\d)")),
]


def decode_bytes(raw: bytes) -> str:
    for enc in ("utf-8-sig", "utf-8", "gb18030"):
        try:
            return raw.decode(enc)
        except UnicodeDecodeError:
            continue
    return raw.decode("utf-8", errors="replace")


def is_pii_header(header: str) -> bool:
    return any(p.search(header.strip()) for p in PII_HEADER_PATTERNS)


def sanitize_csv(input_path: pathlib.Path, output_path: pathlib.Path) -> int:
    text = decode_bytes(input_path.read_bytes())
    rows = list(csv.reader(io.StringIO(text)))
    if not rows:
        print("Input CSV is empty.", file=sys.stderr)
        return 1

    headers = rows[0]
    dropped_cols: list[str] = []
    keep_indices: list[int] = []
    for idx, h in enumerate(headers):
        if is_pii_header(h):
            dropped_cols.append(h.strip())
        else:
            keep_indices.append(idx)

    redacted_cells = 0
    clean_rows: list[list[str]] = [[headers[i] for i in keep_indices]]

    for row in rows[1:]:
        out_row: list[str] = []
        for idx in keep_indices:
            val = row[idx] if idx < len(row) else ""
            for _, rx in CELL_RULES:
                val, count = rx.subn("[REDACTED]", val)
                redacted_cells += count
            out_row.append(val)
        clean_rows.append(out_row)

    # Post-clean verification gate (same rules as server Mode 2)
    residual = []
    for h in clean_rows[0]:
        if is_pii_header(h):
            residual.append(f"header:{h}")
    for r_num, row in enumerate(clean_rows[1:], start=2):
        for c_idx, cell in enumerate(row):
            for label, rx in CELL_RULES:
                if rx.search(cell):
                    residual.append(f"row={r_num},col={clean_rows[0][c_idx]},rule={label}")

    if residual:
        print(f"GATE FAILED — residual PII detected: {residual[:10]}", file=sys.stderr)
        return 2

    buf = io.StringIO()
    writer = csv.writer(buf, lineterminator="\r\n")
    writer.writerows(clean_rows)
    output_path.write_bytes(b"\xef\xbb\xbf" + buf.getvalue().encode("utf-8"))

    print(f"OK — Sanitized locally (0 network calls).")
    print(f"  Input : {input_path}")
    print(f"  Output: {output_path}")
    print(f"  Rows  : {len(clean_rows) - 1}")
    print(f"  Dropped PII columns ({len(dropped_cols)}): {dropped_cols}")
    print(f"  Redacted stray cell values: {redacted_cells}")
    print("  Pre-upload Mode 2 Privacy Gate: PASS (0 PII remaining)")
    return 0


def main(argv: list[str]) -> int:
    if len(argv) < 2 or argv[1] in ("-h", "--help"):
        print("Usage: python local_sanitizer.py <input.csv> [output_sanitized.csv]")
        return 0
    src = pathlib.Path(argv[1]).expanduser().resolve()
    if not src.exists():
        print(f"File not found: {src}", file=sys.stderr)
        return 1
    dst = (
        pathlib.Path(argv[2]).expanduser().resolve()
        if len(argv) >= 3
        else src.with_name(src.stem + "_sanitized.csv")
    )
    return sanitize_csv(src, dst)


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
