"""QA 集計: 件数の漏斗 (対象小問→発番→切り出し→条件確認→解答作成→独立検証→公開可能)、未解決一覧、網羅状況を qa/ に書く。"""
from __future__ import annotations
import json, collections
from common import *

def main():
    cat = load_json(DATA / "catalog.json")
    regions = {r["region_id"]: r for r in load_json(DATA / "regions.json")["regions"]}
    pages = load_json(DATA / "pages.json")["pages"]
    official = load_official()
    subs = [p for p in cat["problems"] if p["kind"] == "sub"]
    f = collections.OrderedDict()
    f["対象小問数 (公式解答欄の数)"] = sum(len(v) for e in official.values() for v in e["answers"].values())
    f["発番済み"] = len(subs)
    f["切り出し済み (main 領域あり)"] = sum(1 for p in subs if p["main_region_ids"])
    f["切り出し目視確認済み"] = sum(1 for p in subs if p["publish_checks"]["crop_visually_checked"])
    f["条件確認済み (転記確認+共通条件)"] = sum(1 for p in subs if p["publish_checks"]["source_mapping_confirmed"] and p["publish_checks"]["shared_context_confirmed"])
    f["解答作成済み"] = sum(1 for p in subs if p.get("solution"))
    f["独立検証済み"] = sum(1 for p in subs if p["publish_checks"]["independent_verification_passed"])
    f["公式解答と一致"] = sum(1 for p in subs if p["publish_checks"]["answer_consistency_checked"])
    f["公開可能"] = sum(1 for p in subs if p["status"]["publish"] == "publishable")
    f["不備問題 (除外)"] = sum(1 for p in subs if p["status"]["flags"].get("defective"))
    hold = collections.Counter()
    for p in subs:
        for r in p["status"]["hold_reasons"]:
            hold[r.split(":")[0]] += 1
    by_exam = collections.OrderedDict()
    for e in cat["exams"]:
        ps = [p for p in subs if p["exam_id"] == e["exam_id"]]
        by_exam[e["exam_id"]] = {"display": e["display_name"], "subs": len(ps), "solution": sum(1 for p in ps if p.get("solution")),
                                 "verified": sum(1 for p in ps if p["publish_checks"]["independent_verification_passed"]),
                                 "visual": sum(1 for p in ps if p["publish_checks"]["crop_visually_checked"]),
                                 "publishable": sum(1 for p in ps if p["status"]["publish"] == "publishable")}
    # 未解決
    unresolved = []
    for p in subs:
        v = p.get("verification") or {}
        if v.get("conflicts_unresolved"): unresolved.append({"problem_id": p["problem_id"], "type": "資料間の不一致", "note": v.get("conflict_note")})
        if p.get("transcript_confirmed") and p["transcript_confirmed"].get("status") == "agent_visual_unclear":
            unresolved.append({"problem_id": p["problem_id"], "type": "判読不能箇所", "note": p["transcript_confirmed"].get("notes")})
        if p["status"]["flags"].get("defective"): unresolved.append({"problem_id": p["problem_id"], "type": "不備問題", "note": p["status"]["flags"].get("reason")})
        if p.get("solution") and not p["publish_checks"]["independent_verification_passed"]:
            unresolved.append({"problem_id": p["problem_id"], "type": "独立検証未通過", "note": "; ".join(m.get("result", "") for m in (v.get("methods") or []) if "不一致" in m.get("result", "") or "エラー" in m.get("result", ""))})
    # 網羅状況: ページ役割 × 領域
    cov = []
    for pg in pages:
        if pg["role"] != "problem": continue
        n = sum(1 for r in regions.values() if r["exam_id"] == pg["exam_id"] and r["page_index"] == pg["page_index"])
        cov.append({"exam_id": pg["exam_id"], "page": pg["page_display"], "regions": n})
    zero = [c for c in cov if c["regions"] == 0]
    save_json(QA / "funnel.json", {"generated_at": now_iso(), "funnel": f, "hold_reasons": hold, "by_exam": by_exam, "unresolved": unresolved,
                                   "problem_pages_without_regions": zero})
    L = [f"# QA 集計 ({now_iso()})", "", "## 件数の漏斗 (単位: 小問)", "", "| 段階 | 件数 |", "|---|---|"]
    L += [f"| {k} | {v} |" for k, v in f.items()]
    L += ["", "数字の整合: 対象小問数 = 発番済み (全21試験・公式解答欄と小問構成が一致)。公開可能 = 独立検証済み ∧ 目視確認済み ∧ 条件確認済み ∧ 公式一致 ∧ 不備なし。", "",
          "## 保留理由 (重複あり)", ""] + [f"- {k}: {v}" for k, v in hold.most_common()]
    L += ["", "## 試験別", "", "| exam | 試験 | 小問 | 解答作成 | 独立検証 | 目視確認 | 公開可能 |", "|---|---|---|---|---|---|---|"]
    L += [f"| {k} | {v['display']} | {v['subs']} | {v['solution']} | {v['verified']} | {v['visual']} | {v['publishable']} |" for k, v in by_exam.items()]
    L += ["", "## 未解決一覧", ""] + ([f"- {u['problem_id']} [{u['type']}] {u['note'] or ''}" for u in unresolved] or ["- なし"])
    L += ["", "## 網羅状況", "", f"- 問題ページ {len(cov)} ページのうち領域ゼロのページ: {len(zero)} {zero if zero else ''}",
          "- 各試験の小問構成は学校公表の解答欄の構成と一致 (data/segmentation/*.json の structure_matches_official)。",
          "- 元資料上の小問総数は解答用紙の欄数で確定できる (21 試験すべてに正解入り解答用紙あり)。"]
    (QA / "qa_report.md").write_text("\n".join(L), encoding="utf-8")
    print(json.dumps(f, ensure_ascii=False))

if __name__ == "__main__":
    main()
