"""独立検証ランナー。scripts/verify/E00xx.py の CHECKS を実行し data/verification/<pid>.json を書く。

各 CHECKS[pid] は dict:
  {"compute": callable -> 値 (Fraction/int/str/tuple), "method": "説明", "expect": 正規化した期待値(公式解答と同値の形),
   "extra": [ (callable, "説明") ... ]  # 追加の確認経路 (真偽値を返す)
  }
比較は Fraction・整数・文字列の厳密一致。浮動小数は使わない (使う場合は Fraction に直す)。
"""
from __future__ import annotations
import importlib, sys, json, re, traceback, hashlib
from fractions import Fraction
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from common import *

def parse_official(raw: str):
    """公式解答文字列 → 比較用の正規形 (Fraction / tuple / str)。"""
    s = raw.strip()
    s = re.sub(r"\s*(cm³|cm²|cm|km|m|g|L|mL|円|個|人|本|枚|通り|番目|回|日間|日|分後|分間|分|秒後|秒間|秒|度|倍|組|種類|歳|脚|杯|問|%)+\s*$", "", s)
    s = s.replace("毎分", "").replace("分速", "").replace("時速", "").replace("午前", "")
    m = re.fullmatch(r"(\d+)と(\d+)/(\d+)", s)
    if m: return Fraction(int(m.group(1)) * int(m.group(3)) + int(m.group(2)), int(m.group(3)))
    m = re.fullmatch(r"(\d+)/(\d+)", s)
    if m: return Fraction(int(m.group(1)), int(m.group(2)))
    m = re.fullmatch(r"\d+(?:\.\d+)?", s)
    if m: return Fraction(s)
    m = re.fullmatch(r"(\d+)\s*[:：]\s*(\d+)(?:\s*[:：]\s*(\d+))?", s)
    if m: return tuple(int(x) for x in m.groups() if x)
    # 記号・文字解答: 空白と区切り記号を除いて比較 ('(ア)(エ)' と '(ア)、(エ)' を同一視)
    return re.sub(r"[\s、,，・/]+", "", s)

def canon(v):
    """文字列は parse_official で正規化してから norm。"""
    return norm(parse_official(v) if isinstance(v, str) else v)

def is_hardcoded(fn) -> bool:
    """compute が定数を返すだけ (独立検証になっていない) かを AST で判定。"""
    import ast, inspect, textwrap
    try:
        src = textwrap.dedent(inspect.getsource(fn))
    except (OSError, TypeError):
        return False
    try:
        tree = ast.parse(src)
    except SyntaxError:
        # 辞書内の lambda は行全体が取れるので式として再解析
        try:
            tree = ast.parse(src.strip().rstrip(",}"))
        except SyntaxError:
            return False
    for node in ast.walk(tree):
        if isinstance(node, ast.Lambda):
            b = node.body
            if isinstance(b, ast.Constant): return True
            if isinstance(b, (ast.Tuple, ast.List)) and all(isinstance(e, ast.Constant) for e in b.elts): return True
            if isinstance(b, ast.UnaryOp) and isinstance(b.operand, ast.Constant): return True
            if isinstance(b, ast.Call) and getattr(b.func, "id", "") in ("F", "Fraction") and all(isinstance(a, ast.Constant) for a in b.args): return True
            return False
        if isinstance(node, ast.FunctionDef):
            body = [n for n in node.body if not isinstance(n, ast.Expr) or not isinstance(getattr(n, "value", None), ast.Constant)]
            if len(body) == 1 and isinstance(body[0], ast.Return):
                r = body[0].value
                if isinstance(r, ast.Constant) or (isinstance(r, (ast.Tuple, ast.List)) and all(isinstance(e, ast.Constant) for e in r.elts)):
                    return True
            return False
    return False

def norm(v):
    if isinstance(v, (int,)): return Fraction(v)
    if isinstance(v, float): raise TypeError("浮動小数は不可: Fraction を使う")
    if isinstance(v, (list,)): return tuple(v)
    return v

def main(only=None):
    official = load_official()
    import importlib.util
    total = passed = 0
    for script in sorted(list((ROOT / "scripts" / "verify").glob("TOYO-E*.py")) + list((ROOT / "scripts" / "verify").glob("JG-E*.py"))):
        if only and script.stem not in only: continue
        spec = importlib.util.spec_from_file_location(script.stem, script); mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)
        for pid, chk in mod.CHECKS.items():
            total += 1
            eid = exam_of(pid); qn = pid.split("-Q")[1][:2]; sn = pid.split("-S")[1][:2]
            raw = official.get(eid, {}).get("answers", {}).get(f"Q{qn}", {}).get(f"S{sn}")
            res = {"problem_id": pid, "script": rel(script), "at": now_iso(), "methods": [], "official": raw}
            try:
                if is_hardcoded(chk["compute"]):
                    raise RuntimeError("compute が定数を返すだけ (独立検証になっていない)。別経路で計算すること")
                val = canon(chk["compute"]())
                res["computed"] = str(val)
                exp = canon(chk["expect"]) if "expect" in chk else (parse_official(raw) if raw else None)
                ok = (val == exp)
                res["methods"].append({"method": chk["method"], "result": f"計算値 {val} / 期待値 {exp} → {'一致' if ok else '不一致'}", "by": "verification_script"})
                off_ok = None
                if raw is not None:
                    po = parse_official(raw)
                    ov = chk.get("official_value", chk.get("expect"))
                    off_ok = (canon(ov) == po) if ("official_value" in chk or "expect" in chk) else (val == po)
                    res["methods"].append({"method": "学校公表の正解との照合", "result": f"公式 {raw!r} → {'一致' if off_ok else '不一致'}", "by": "verification_script"})
                for fn, desc in chk.get("extra", []):
                    r2 = bool(fn()); ok = ok and r2
                    res["methods"].append({"method": desc, "result": "成立" if r2 else "不成立", "by": "verification_script"})
                res["passed"] = bool(ok); res["official_match"] = off_ok
                res["conflicts_unresolved"] = bool(chk.get("conflict_unresolved", False))
                if "conflict_note" in chk: res["conflict_note"] = chk["conflict_note"]
            except Exception as e:
                res["passed"] = False; res["official_match"] = None; res["error"] = traceback.format_exc()[-800:]
            # content signature (解答・本文に紐付ける)
            try:
                cpath = ROOT / "content" / f"{eid}.py"
                spec_c = importlib.util.spec_from_file_location(eid.replace("-", "_"), cpath); mod_c = importlib.util.module_from_spec(spec_c); spec_c.loader.exec_module(mod_c)
                rec = mod_c.RECORDS.get(pid)
                if rec:
                    from build_problems import sig
                    res["content_sig"] = sig(rec)
                    # 解答文字列と計算値の整合 (final_answer をパースして比較)
                    fa = canon(str(rec["solution"]["final_answer"]))
                    fa_ok = (fa == canon(chk["compute"]())) if "expect" not in chk else (fa == canon(chk["expect"]))
                    res["methods"].append({"method": "カード解答(final_answer)と計算値の整合", "result": "一致" if fa_ok else f"不一致 (解答 {fa})", "by": "verification_script"})
                    res["passed"] = res["passed"] and fa_ok
            except Exception as e:
                res["content_sig"] = None; res["methods"].append({"method": "content 連携", "result": f"エラー {e}", "by": "verification_script"})
            passed += bool(res.get("passed"))
            save_json(DATA / "verification" / f"{pid}.json", res)
    print(f"verification: {passed}/{total} passed")
    (QA / "verification_summary.txt").write_text(f"{now_iso()} verification: {passed}/{total} passed\n", encoding="utf-8")

if __name__ == "__main__":
    main(set(sys.argv[1:]) or None)
