#!/usr/bin/env python3
from __future__ import annotations

import argparse
import json
import re
import shutil
import subprocess
from pathlib import Path


UNSUPPORTED_CLAIMS = ["毫秒级", "极速", "高精度", "百分百", "100%", "零误差"]


def normalize(text: str) -> str:
    return re.sub(r"\s+", "", text).replace("：", "").replace(":", "")


def main() -> int:
    parser = argparse.ArgumentParser(description="OCR-audit a SKU infographic against its frozen manifest flow.")
    parser.add_argument("--manifest", required=True, type=Path)
    parser.add_argument("--image", required=True, type=Path)
    args = parser.parse_args()
    if not shutil.which("tesseract"):
        print(json.dumps({"status": "BLOCKED", "errors": ["tesseract not found"]}, ensure_ascii=False))
        return 2
    data = json.loads(args.manifest.read_text(encoding="utf-8"))
    proc = subprocess.run(
        ["tesseract", str(args.image), "stdout", "-l", "chi_sim+eng", "--psm", "6"],
        text=True, capture_output=True, check=False,
    )
    text = proc.stdout
    compact = normalize(text)
    errors = [claim for claim in UNSUPPORTED_CLAIMS if claim in compact]
    missing = [step for step in data["main_flow"] if normalize(step) not in compact]
    result = {
        "status": "PASS" if not errors else "FAIL",
        "sku": data["sku"],
        "unsupported_claims": errors,
        "flow_labels_not_found_by_ocr": missing,
        "ocr_text": text.strip(),
    }
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0 if not errors else 1


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