"""content/E00xx.py の RECORDS を data/problems/<pid>.json に書き出す。
検証結果 (data/verification/<pid>.json, scripts/verify/run_all.py が生成) と目視確認 (data/regions.json visual_check) を併合し、
公開判定に必要な checks を組み立てる。既存JSONと内容が同じなら content_version を維持し、解答・本文・主解法が変わった場合は
content_version を上げて independent_verification を無効化する (再検証が必要)。
"""
from __future__ import annotations
import importlib, sys, json, hashlib
from pathlib import Path
from common import *

sys.path.insert(0, str(ROOT))

SIGNIFICANT = ["transcript", "solution"]   # 変更で再検証が必要になる部分

def sig(rec):
    return hashlib.sha256(json.dumps({k: rec.get(k) for k in SIGNIFICANT}, ensure_ascii=False, sort_keys=True).encode()).hexdigest()

def main(only=None):
    regions = {r["region_id"]: r for r in load_json(DATA / "regions.json")["regions"]}
    segs = {}
    for p in (DATA / "segmentation").glob("*.json"):
        d = load_json(p)
        for pr in d["problems"]: segs[pr["problem_id"]] = pr
    n_new = n_upd = n_same = 0
    import importlib.util
    for mod_path in sorted(list((ROOT / "content").glob("TOYO-E*.py")) + list((ROOT / "content").glob("JG-E*.py"))):
        if only and mod_path.stem not in only: continue
        spec = importlib.util.spec_from_file_location(mod_path.stem.replace("-", "_"), mod_path)
        mod = importlib.util.module_from_spec(spec)
        try:
            spec.loader.exec_module(mod)
        except Exception as e:
            print(f"!! {mod_path.name} の読み込みに失敗 (スキップ): {type(e).__name__}: {e}"); continue
        for pid, rec in mod.RECORDS.items():
            assert pid in segs, f"{pid} はセグメンテーションに存在しない"
            out = DATA / "problems" / f"{pid}.json"
            old = load_json(out, {})
            ver = load_json(DATA / "verification" / f"{pid}.json", {})
            new_sig = sig(rec)
            if not old:
                cv = CONTENT_VERSION; changelog = [{"version": cv, "at": now_iso(), "reason": "初版"}]; n_new += 1
            elif old.get("_sig") != new_sig:
                cv = (old.get("content_version") or 1) + 1
                changelog = old.get("changelog", []) + [{"version": cv, "at": now_iso(), "reason": "本文・解答・主解法のいずれかを変更 (再検証が必要)", "previous_sig": old.get("_sig")}]
                n_upd += 1
            else:
                cv = old.get("content_version") or 1; changelog = old.get("changelog", []); n_same += 1
            # 検証結果はコンテンツ版が一致するときだけ有効
            ver_ok = ver.get("content_sig") == new_sig
            sub = segs[pid]
            main_r = [rid for rid in sub.get("region_ids", []) if regions[rid]["role"] in ("main", "continuation")]
            stem_r = sub.get("stem_region_ids", [])
            vis = bool(main_r or stem_r) and all((regions[rid].get("visual_check") or {}).get("ok") for rid in main_r + stem_r)
            sol = rec["solution"]
            checks = {
                "source_mapping_confirmed": bool(main_r) and rec["transcript"]["status"].endswith("confirmed"),
                "crop_visually_checked": vis,
                "shared_context_confirmed": bool(rec.get("_shared_context_ok", True)) and (rec["transcript"]["status"].endswith("confirmed")),
                "answer_consistency_checked": ver_ok and ver.get("official_match") is True,
                "independent_verification_passed": ver_ok and ver.get("passed") is True,
                "no_unresolved_conflicts": ver_ok and not ver.get("conflicts_unresolved"),
                "explanation_reproducible": bool(sol["steps"]) and bool(sol["first_insight"]) and bool(sol["check"]) and rec["transcript"]["status"].endswith("confirmed"),
                "no_answer_leak_on_front": not any(answer_leaks(str(sol["final_answer"]), h or "") for h in rec["hints"]),
            }
            methods = ver.get("methods", []) if ver_ok else []
            for m in rec.get("verification_methods_declared", []):
                methods.append({"method": m, "result": "宣言のみ(スクリプト未実行)" , "by": "agent"})
            record = {**rec, "content_version": cv, "changelog": changelog, "_sig": new_sig,
                      "verification": {"checks": checks, "methods": methods, "script": ver.get("script") if ver_ok else None,
                                       "verified_at": ver.get("at") if ver_ok else None, "verified_by": "verification_script+agent" if ver_ok else None,
                                       "official_answer": ver.get("official") if ver_ok else None, "computed": ver.get("computed") if ver_ok else None,
                                       "conflicts_unresolved": ver.get("conflicts_unresolved", False) if ver_ok else False,
                                       "stale": (not ver_ok) and bool(ver)},
                      "updated_at": now_iso()}
            save_json(out, record)
    print(f"problems: new {n_new}, updated {n_upd}, unchanged {n_same}")

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