"""全体分析用の集計 (analysis/01_出題構造の集計.md と analysis/stats.json)。
- 集計単位と分母を必ず付ける (試験数 / 大問数 / 小問数)。複数タグの集計は合計が 100% を超え得る。
- 内容確認済み (解答作成済み) の小問だけを分野・核の集計対象にし、未確認数を明示する。
"""
from __future__ import annotations
import collections, json
from common import *

def pct(a, b): return f"{a} ({100*a/b:.0f}%)" if b else "-"

def main(school: str = "TOYO"):
    cat = load_json(DATA / "catalog.json")
    cat["exams"] = [e for e in cat["exams"] if e.get("school_code", "TOYO") == school]
    cat["problems"] = [p for p in cat["problems"] if p.get("school_code", "TOYO") == school]
    outdir = (ROOT / "analysis") if school == "TOYO" else (ROOT / "analysis" / school.lower())
    outdir.mkdir(parents=True, exist_ok=True)
    exams = cat["exams"]; subs = [p for p in cat["problems"] if p["kind"] == "sub"]; majors = [p for p in cat["problems"] if p["kind"] == "major"]
    analyzed = [p for p in subs if p.get("analysis") and p["analysis"].get("primary_field")]
    n_ex, n_maj, n_sub, n_an = len(exams), len(majors), len(subs), len(analyzed)
    L = [f"# 出題構造の集計 ({now_iso()[:10]})", "",
         f"分母: 試験 {n_ex}、大問 {n_maj}、小問 {n_sub}。分野・核の集計は内容確認済み (解答作成済み) の小問 {n_an} 件のみ。未分類 {n_sub - n_an} 件は集計に含めず、年度の偏りに注意 (下表)。", ""]
    # 1. 構成
    L += ["## 1. 試験ごとの構成 (大問数 / 小問数 / 小問の並び)", "", "| 試験 | 大問 | 小問 | 各大問の小問数 | 前問依存の小問 | 分析済み |", "|---|---|---|---|---|---|"]
    for e in exams:
        ms = [m for m in majors if m["exam_id"] == e["exam_id"]]
        ss = [p for p in subs if p["exam_id"] == e["exam_id"]]
        dep = sum(1 for p in ss if p.get("depends_on"))
        an = sum(1 for p in ss if p.get("analysis") and p["analysis"].get("primary_field"))
        L.append(f"| {e['display_name']} | {len(ms)} | {len(ss)} | {'-'.join(str(len(m['sub_ids'])) for m in ms)} | {dep} | {an}/{len(ss)} |")
    # 2. 分野 (主分野, 単一タグ)
    L += ["", "## 2. 主分野の出現 (単位: 小問。分母 = 分析済み小問数。単一タグなので合計 100%)", ""]
    by_field = collections.Counter(p["analysis"]["primary_field"] for p in analyzed)
    L += ["| 主分野 | 小問数 (割合) |", "|---|---|"] + [f"| {k} | {pct(v, n_an)} |" for k, v in by_field.most_common()]
    # 年度別
    years = sorted({e["year"] for e in exams})
    L += ["", "### 年度×主分野 (小問数。分母は各年度の分析済み小問数)", "", "| 主分野 | " + " | ".join(str(y) for y in years) + " |", "|---|" + "---|" * len(years)]
    for fld, _ in by_field.most_common():
        row = []
        for y in years:
            ps = [p for p in analyzed if p["year"] == y]; row.append(pct(sum(1 for p in ps if p["analysis"]["primary_field"] == fld), len(ps)))
        L.append(f"| {fld} | " + " | ".join(row) + " |")
    L.append("| (分析済み小問数) | " + " | ".join(str(sum(1 for p in analyzed if p["year"] == y)) for y in years) + " |")
    # 3. 数学的な核 (複数タグ)
    L += ["", "## 3. 数学的な核の出現 (単位: 小問。複数タグ可 → 割合の合計は 100% を超える)", ""]
    cores = collections.Counter(c for p in analyzed for c in p["analysis"].get("cores_canonical", []))
    L += ["| 核 | 小問数 (割合) | 出現する問題ID (最大6) |", "|---|---|---|"]
    for k, v in cores.most_common(60):
        ids = [p["problem_id"] for p in analyzed if k in p["analysis"].get("cores_canonical", [])][:6]
        L.append(f"| {k} | {pct(v, n_an)} | {', '.join(ids)} |")
    # 4. 核の組合せ (大問単位)
    L += ["", "## 4. 大問内での核の組合せ (単位: 大問。同一大問の小問の核を合わせた集合。分母 = 分析済み小問を含む大問数)", ""]
    combos = collections.Counter(); n_mj = 0
    for m in majors:
        ss = [p for p in analyzed if p["parent_id"] == m["problem_id"]]
        if not ss: continue
        n_mj += 1
        cs = tuple(sorted({c for p in ss for c in p["analysis"].get("cores_canonical", [])}))
        if len(cs) >= 2: combos[cs] += 1
    L += ["| 核の組合せ | 大問数 |", "|---|---|"] + [f"| {' + '.join(k)} | {v} |" for k, v in combos.most_common(25)] + [f"", f"(分母: {n_mj} 大問)"]
    # 5. 難度・時間
    L += ["", "## 5. 難度 (分析者の暫定評価, A〜D) と目安時間 (推定) ・ 位置", ""]
    diff = collections.Counter(p["learning"]["difficulty"] for p in analyzed if p.get("learning"))
    L += ["| 難度 | 小問数 |", "|---|---|"] + [f"| {k} | {v} |" for k, v in sorted(diff.items())]
    L += ["", "### 大問番号 × 難度 (小問数)", "", "| 大問 | A | B | C | D | 平均目安時間(分) |", "|---|---|---|---|---|---|"]
    qmax = max([int(p["problem_id"].split("-Q")[1][:2]) for p in analyzed] or [6])
    for q in range(1, qmax + 1):
        ps = [p for p in analyzed if int(p["problem_id"].split("-Q")[1][:2]) == q]
        cnt = collections.Counter(p["learning"]["difficulty"] for p in ps)
        est = [p["learning"]["est_minutes"] for p in ps if p["learning"].get("est_minutes")]
        L.append(f"| {q} | {cnt.get('A',0)} | {cnt.get('B',0)} | {cnt.get('C',0)} | {cnt.get('D',0)} | {sum(est)/len(est):.1f} |" if est else f"| {q} | - | - | - | - | - |")
    tot = [p["learning"]["est_minutes"] for p in analyzed if p["learning"].get("est_minutes")]
    fmt = (CONFIG.get("schools", {}).get(school, {}) or {}).get("exam_format_note", "試験時間は資料に記載が無く未確認")
    L += ["", f"分析済み小問の目安時間の合計 (推定): {sum(tot):.0f} 分 / {n_an} 問 → 1試験あたり平均 {sum(tot)/max(1,len({p['exam_id'] for p in analyzed})):.0f} 分 ({fmt})。"]
    # 6. 障壁
    L += ["", "## 6. 主な障壁 (小問数, 複数可)", ""]
    bar = collections.Counter(b for p in analyzed for b in (p["analysis"].get("barrier") or "").split("・") if b)
    L += ["| 障壁 | 小問数 (割合) |", "|---|---|"] + [f"| {k} | {pct(v, n_an)} |" for k, v in bar.most_common()]
    # 7. 前提技能
    L += ["", "## 7. 前提技能の出現 (小問数, 複数可)", ""]
    pre = collections.Counter(x for p in analyzed for x in p["analysis"].get("prereq_canonical", []))
    L += ["| 前提技能 | 小問数 | 問題ID (最大5) |", "|---|---|---|"]
    for k, v in pre.most_common(60):
        ids = [p["problem_id"] for p in analyzed if k in p["analysis"].get("prereq_canonical", [])][:5]
        L.append(f"| {k} | {v} | {', '.join(ids)} |")
    (outdir / "01_出題構造の集計.md").write_text("\n".join(L), encoding="utf-8")
    save_json(outdir / "stats.json", {"generated_at": now_iso(), "n_exams": n_ex, "n_majors": n_maj, "n_subs": n_sub, "n_analyzed": n_an,
                                                 "fields": by_field, "cores": cores, "difficulty": diff, "barriers": bar, "prerequisites": pre})
    print(f"analysis stats: analyzed {n_an}/{n_sub}")

if __name__ == "__main__":
    import sys
    main(sys.argv[1] if len(sys.argv) > 1 else "TOYO")
