#!/usr/bin/env python3
"""Smoke rubric: keyword/heuristic check that a restatement surfaces ambiguities.

Not a model judge. Intended for fixtures/sample-restatement-miss.md (expect FAIL)
or a careful human restatement (may PASS). Exit 1 = weak detection / miss.
"""
from __future__ import annotations

import re
import sys
from pathlib import Path

# Must-catch themes from fixtures/expected-ambiguities.md (ZH+EN cues)
THEMES = [
    ("default_value", re.compile(r"默认|default\s*(value|on|off|true|false)?", re.I)),
    ("storage", re.compile(r"持久化|存储|存哪|settings\s*table|user_preferences|storage|persisted", re.I)),
    ("channel_scope", re.compile(r"通道|邮件|推送|短信|站内|email|push|sms|channel|category", re.I)),
    ("who_can_edit", re.compile(r"谁可|可见|本人|管理员|权限|who\s+can|visibility|admin|auth", re.I)),
    ("failure_rollback", re.compile(r"回滚|失败|重试|rollback|fail(?:ure)?|retry|toast", re.I)),
    ("preference_link", re.compile(r"schema|字段|API|/api/|未定义|undefined|never\s+defines|no\s+link", re.I)),
    ("transactional_boundary", re.compile(r"验证码|事务|账单|transactional|security|otp|已在途|in[- ]flight", re.I)),
    ("blocker_or_undef_section", re.compile(r"blocker|未定义|undefined\s+term|assumed\s+setup|解释不回", re.I)),
]

PASS_THRESHOLD = 0.7  # fraction of themes that must hit


def score(text: str) -> tuple[float, list[str], list[str]]:
    hit, miss = [], []
    for name, pat in THEMES:
        if pat.search(text):
            hit.append(name)
        else:
            miss.append(name)
    return (len(hit) / len(THEMES), hit, miss)


def main(argv: list[str]) -> int:
    if len(argv) != 2:
        print("Usage: score_restatement.py <restatement.md>", file=sys.stderr)
        return 2
    path = Path(argv[1])
    text = path.read_text(encoding="utf-8")
    ratio, hit, miss = score(text)
    print(f"file: {path}")
    print(f"themes_hit: {len(hit)}/{len(THEMES)} ({ratio:.0%})")
    print(f"hit: {', '.join(hit) or '(none)'}")
    print(f"miss: {', '.join(miss) or '(none)'}")
    # Extra fail signal: inventing defaults without marking uncertainty
    invents = bool(re.search(r"I assume|我假定|我假设|默认关闭|默认打开", text, re.I))
    empty_blockers = bool(re.search(r"Blockers\s*\n\s*([-*-]\s*)?(None|无|没有)", text, re.I))
    if invents and empty_blockers:
        print("signal: invented_boundaries_with_empty_blockers")
    if ratio < PASS_THRESHOLD or (invents and empty_blockers):
        print("result: FAIL (weak detection or invented boundaries)")
        return 1
    print("result: PASS (smoke heuristics only)")
    return 0


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