"""qa/official_answers_check.md: 公式解答の転記と独立検証の照合結果、不一致・未検証の一覧。"""
import json, glob
from common import *
official = load_official()
ver = {json.load(open(f))["problem_id"]: json.load(open(f)) for f in glob.glob(str(DATA / "verification" / "*.json"))}
cat = load_json(DATA / "catalog.json")
subs = [p for p in cat["problems"] if p["kind"] == "sub"]
L = [f"# 公式解答 (学校作成の正解) と独立検証の照合 ({now_iso()[:10]})", "",
     "公式解答はエージェントが解答用紙画像を目視して転記した (data/official_answers.json)。各小問の独立検証 (scripts/verify) の計算値と照合し、不一致は原因を調べた。", "",
     "| 試験 | 小問 | 公式一致 | 検証通過 | 不一致・未検証の内訳 |", "|---|---|---|---|---|"]
rows_bad = []
for e in cat["exams"]:
    ps = [p for p in subs if p["exam_id"] == e["exam_id"]]
    match = sum(1 for p in ps if (ver.get(p["problem_id"]) or {}).get("official_match"))
    passed = sum(1 for p in ps if (ver.get(p["problem_id"]) or {}).get("passed"))
    bad = []
    for p in ps:
        v = ver.get(p["problem_id"])
        if not v: bad.append(f"{p['problem_id'].split('-',2)[2]}: 未検証"); continue
        if v.get("official_match") is False: bad.append(f"{p['problem_id'].split('-',2)[2]}: 公式不一致 (計算 {v.get('computed')} / 公式 {v.get('official')})"); rows_bad.append(p["problem_id"])
        elif not v.get("passed"): bad.append(f"{p['problem_id'].split('-',2)[2]}: 検証不通過"); rows_bad.append(p["problem_id"])
    L.append(f"| {e['exam_id']} {e['display_name']} | {len(ps)} | {match} | {passed} | {'; '.join(bad)} |")
L += ["", "## 不一致・不通過の詳細", ""]
for pid in rows_bad:
    v = ver[pid]; L.append(f"### {pid}"); L += [f"- {m['method']}: {m['result']}" for m in v.get("methods", [])]
    if v.get("error"): L.append("- error: " + v["error"].strip().splitlines()[-1])
    if v.get("conflict_note"): L.append("- 注記: " + v["conflict_note"])
    L.append("")
if not rows_bad: L.append("- なし")
(QA / "official_answers_check.md").write_text("\n".join(L), encoding="utf-8"); print("bad", len(rows_bad))
