"""カタログの構築 (data/catalog.json と db/catalog.sqlite を再生成する)。

正本 (source of truth) は data/ 配下の個別JSON:
  sources.json, exams.json, pages.json, segmentation/<exam>.json, regions.json, official_answers.json,
  transcripts_auto.json (自動ドラフト), transcripts.json (確認済み転記),
  lecture_map.json (塾解説の対応), problems/<problem_id>.json (解答・分析・検証・状態),
  status_overrides.json (保留・一時停止などの運用上書き)
catalog.json / catalog.sqlite は派生物であり、再生成で常に同じ内容になる。学習履歴は db/study.sqlite に分離。
"""
from __future__ import annotations
import re, sqlite3, glob, collections
from common import *
import json

REQUIRED_CHECKS = CONFIG["publish"]["required_checks"]
TAXONOMY = load_json(DATA / "core_taxonomy.json", {"cores": [], "prerequisites": []})
UNMAPPED = {"cores": collections.Counter(), "prerequisites": collections.Counter()}

# どの規則にも当てはまらない核は、小問の主分野に対応する代表の核に落とす (qa/taxonomy_unmapped.json には残るので語彙の追加で解消する)。
FIELD_FALLBACK = {
    "cores": {"計算": "計算の工夫", "数の性質": "余り・倍数・偶奇による分類", "規則性": "数列・規則の一般化", "場合の数": "場合分け・数え上げ",
              "割合と比": "割合の操作 (濃度・売買・平均・てんびん)", "文章題": "消去算・連立・つるかめ", "速さ": "速さの構造 (旅人算・往復・ダイヤグラム・時計・流水・通過)",
              "平面図形": "面積・周の長さの基本公式", "立体図形": "体積の計算法 (柱・錐・相似・差し引き)", "図形の移動": "図形の移動・通過領域",
              "水そう・グラフ": "水そう・入れ替えの収支", "論理・推理": "定義の読解・条件整理", "統計": "統計量 (平均・中央値・最頻値)"},
    "prerequisites": {},
}

def canon(kind: str, raw: str, field: str = None) -> str:
    for name, kws in TAXONOMY.get(kind, []):
        if any(k in raw for k in kws):
            return name
    UNMAPPED[kind][raw] += 1
    return FIELD_FALLBACK.get(kind, {}).get(field, "その他")

def canon_list(kind: str, raws, field: str = None) -> list:
    out = []
    for r in raws:
        r = r if isinstance(r, str) else (r or {}).get("skill", "")
        if not r: continue
        c = canon(kind, r, field)
        if c not in out: out.append(c)
    return out

def parse_lecture_key(stem: str):
    m = re.match(r"kakomon_(?:v-)?tg-toshima(\d\d)(_second)?_(\d+)[-_](\d+)_c\d+(_alt\d+)?$", stem)
    if not m: return None
    year = 2000 + int(m.group(1)); rnd = 2 if m.group(2) else 1
    return year, rnd, int(m.group(3)), int(m.group(4)), bool(m.group(5))

def build_lecture_map(exams):
    """塾解説JSON (video_summary/out/*.json) と catalog.json を問題IDに対応付ける。"""
    # 塾解説 (video_summary) は豊島岡の過去問の解説動画なので、豊島岡の試験にだけ対応付ける。
    # (女子学院は年度・回 (round=1) が豊島岡の第1回と衝突するため、学校で絞らないと取り違える)
    by_yr = {(e["year"], e["round"]): e["exam_id"] for e in exams if e.get("school_code", "TOYO") == "TOYO"}
    cat = load_json(LECTURE_DIR / "out" / "catalog.json", {})
    lm = {"generated_at": now_iso(), "entries": [], "unmatched": []}
    for p in sorted((LECTURE_DIR / "out").glob("kakomon_*.json")):
        stem = p.stem
        k = parse_lecture_key(stem)
        if not k:
            lm["unmatched"].append({"file": rel(p), "reason": "ファイル名の形式が想定外"}); continue
        year, rnd, q, s_, alt = k
        d = load_json(p)
        nprob = len(d.get("problems", []))
        catkey = f"tg-toshima{year-2000:02d}{'_second' if rnd==2 else ''}_{q}_{s_}"
        meta = cat.get(catkey)
        eid = by_yr.get((year, rnd))
        entry = {"file": rel(p), "sha256": sha256_file(p), "year": year, "round": rnd, "major": q, "sub": s_,
                 "is_alternate": alt, "n_problems_in_file": nprob, "catalog_key": catkey,
                 "catalog_meta": {k2: meta.get(k2) for k2 in ("exam", "title", "difficulty", "level", "fields")} if meta else None,
                 "frames_dir": rel(LECTURE_DIR / "out" / "frames" / stem) if (LECTURE_DIR / "out" / "frames" / stem).exists() else None,
                 "kind": "gemini_structured_notes(動画の文字起こし+板書LaTeX, タイムスタンプ付き)"}
        if eid:
            entry["problem_id"] = sub_id(eid, q, s_)
            entry["match_basis"] = "ファイル名の年度・回・番号 (内容照合は solutions 作成時に実施)"
            lm["entries"].append(entry)
        else:
            entry["reason"] = f"{year}年度 第{rnd}回 の問題PDFが資料に無い"
            lm["unmatched"].append(entry)
    save_json(DATA / "lecture_map.json", lm)
    return lm

def parse_answer(raw: str):
    """公式解答文字列を構造化 (値・単位)。複合解答は raw のまま。"""
    if raw is None: return None
    s = raw.strip()
    m = re.fullmatch(r"(\d+)と(\d+)/(\d+)\s*([^\d\s]*)", s)
    if m:
        a, b, c = int(m.group(1)), int(m.group(2)), int(m.group(3))
        return {"type": "mixed_number", "whole": a, "num": b, "den": c, "value_num": a * c + b, "value_den": c, "unit": m.group(4) or None, "raw": s}
    m = re.fullmatch(r"(\d+)/(\d+)\s*([^\d\s]*)", s)
    if m:
        return {"type": "fraction", "num": int(m.group(1)), "den": int(m.group(2)), "unit": m.group(3) or None, "raw": s}
    m = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([^\d\s:：]*)", s)
    if m:
        return {"type": "number", "value": m.group(1), "unit": m.group(2) or None, "raw": s}
    m = re.fullmatch(r"(\d+)\s*[:：]\s*(\d+)(?:\s*[:：]\s*(\d+))?", s)
    if m:
        return {"type": "ratio", "parts": [int(x) for x in m.groups() if x], "raw": s}
    return {"type": "text", "raw": s}

def main():
    sources = {s["source_id"]: s for s in load_json(DATA / "sources.json")["sources"]}
    exams = load_json(DATA / "exams.json")["exams"]
    regions = {r["region_id"]: r for r in load_json(DATA / "regions.json")["regions"]}
    official = load_official()
    tauto = load_json(DATA / "transcripts_auto.json", {"regions": {}})["regions"]
    tver = load_json(DATA / "transcripts.json", {"regions": {}})["regions"]
    status_over = load_json(DATA / "status_overrides.json", {"problems": {}})["problems"]
    lm = build_lecture_map(exams)
    lec_by_pid = {}
    for en in lm["entries"]:
        lec_by_pid.setdefault(en["problem_id"], []).append(en)
    problems, order = [], 0
    for e in exams:
        seg = load_json(DATA / "segmentation" / f"{e['exam_id']}.json")
        off = official.get(e["exam_id"], {})
        for p in seg["problems"]:
            pid = p["problem_id"]
            rec_path = DATA / "problems" / f"{pid}.json"
            rec = load_json(rec_path, {})
            if p["kind"] == "major":
                order += 1
                problems.append({
                    "problem_id": pid, "kind": "major", "exam_id": e["exam_id"], "parent_id": None, "school_code": e.get("school_code", "TOYO"),
                    "number": p["number"], "display": f"{e['display_name']} 大問{p['number']}", "order_index": order,
                    "region_ids": p.get("region_ids", []), "sub_ids": p["subs"],
                    "content_version": rec.get("content_version", CONTENT_VERSION)})
                continue
            order += 1
            qn, sn = int(pid.split("-Q")[1][:2]), p["number"]
            off_kind = off.get("source_kind", "school")
            raw_ans = off.get("answers", {}).get(f"Q{qn:02d}", {}).get(f"S{sn:02d}")
            main_regions = [rid for rid in p.get("region_ids", []) if regions[rid]["role"] in ("main", "continuation")]
            stem_regions = p.get("stem_region_ids", [])
            transcript = None
            for rid in stem_regions + main_regions:
                v = tver.get(rid)
                a = tauto.get(rid, {})
                transcript = transcript or {}
                transcript[rid] = {"verified": v, "auto": a.get("text"), "status": (v or {}).get("status") or a.get("status", "unavailable")}
            flags = p.get("flags", {})
            if rec.get("analysis"):
                rec["analysis"]["cores_canonical"] = canon_list("cores", rec["analysis"].get("cores", []), rec["analysis"].get("primary_field"))
                rec["analysis"]["prereq_canonical"] = canon_list("prerequisites", rec["analysis"].get("prerequisites", []))
            sol = rec.get("solution")
            ver = rec.get("verification", {})
            checks = {k: bool(ver.get("checks", {}).get(k)) for k in REQUIRED_CHECKS}
            # 切り出し目視確認は regions.json の visual_check を反映
            vis = all((regions[rid].get("visual_check") or {}).get("ok") for rid in main_regions + stem_regions) if (main_regions or stem_regions) else False
            checks["crop_visually_checked"] = checks["crop_visually_checked"] or vis
            so = status_over.get(pid, {})
            hold = []
            if flags.get("defective"): hold.append("原本が不備問題 (出題不能)")
            if raw_ans is None: hold.append("公式解答が無い")
            if not sol: hold.append("解答未作成")
            missing = [k for k, v in checks.items() if not v]
            if missing: hold.append("未確認: " + ", ".join(missing))
            if so.get("suspended"): hold.append("一時停止: " + so.get("reason", ""))
            if ver.get("conflicts_unresolved"): hold.append("資料間の不一致が未解決")
            publishable = not hold
            extraction_status = "visually_checked" if vis else "cropped"
            answer_status = ("independently_verified" if checks["independent_verification_passed"] else "drafted") if sol else ("official_only" if raw_ans else "none")
            problems.append({
                "problem_id": pid, "kind": "sub", "exam_id": e["exam_id"], "parent_id": p["parent_id"],
                "number": sn, "printed": p["printed"], "display": f"{e['display_name']} 大問{qn} ({sn})", "order_index": order,
                "year": e["year"], "round": e["round"], "subject": "算数", "school_code": e.get("school_code", "TOYO"), "school": e.get("school"),
                "year_round_basis": e.get("year_round_basis"), "year_round_verified": e.get("year_round_verified", False),
                "source_refs": [{"region_id": rid, "role": regions[rid]["role"], "source_id": regions[rid]["source_id"],
                                 "page_display": regions[rid]["page_display"], "printed_page": regions[rid]["printed_page"],
                                 "rect_pt": regions[rid]["rect_pt"], "image_path": regions[rid]["image_path"],
                                 "image_sha256": regions[rid]["image_sha256"], "note": regions[rid].get("note")}
                                for rid in stem_regions + main_regions],
                "stem_region_ids": stem_regions, "main_region_ids": main_regions,
                "transcript": transcript, "transcript_confirmed": rec.get("transcript"),
                "depends_on": rec.get("depends_on", []),
                "official_answer": {"raw": raw_ans, "structured": parse_answer(raw_ans),
                                    "source_id": off.get("source_id"), "page_index": off.get("page_index"),
                                    "transcribed_by": off.get("transcribed_by"), "scoring_note": off.get("scoring_note"),
                                    "source_kind": off_kind, "needs_check": off.get("needs_check", False),
                                    "label": "学校公表の正解" if off_kind == "school" else "出版社作成の解答 (学校公表ではない)"} if raw_ans else None,
                "solution": sol, "hints": rec.get("hints"), "analysis": rec.get("analysis"), "learning": rec.get("learning"),
                "teacher": rec.get("teacher"), "references": {"lecture": lec_by_pid.get(pid, []), "teaching_notes": rec.get("teaching_notes_refs", []),
                                                             "other": rec.get("references", [])},
                "verification": ver, "publish_checks": checks,
                "status": {"extraction": extraction_status, "answer": answer_status,
                           "publish": "publishable" if publishable else "hold", "hold_reasons": hold,
                           "flags": flags, "suspended": bool(so.get("suspended"))},
                "content_version": rec.get("content_version", CONTENT_VERSION), "changelog": rec.get("changelog", []),
            })
    cat = {"generated_at": now_iso(), "schema_version": 1, "id_prefix": ID_PREFIX,
           "exams": exams, "problems": problems,
           "schools": SCHOOLS,
           "counts": {"exams": len(exams), "majors": sum(1 for p in problems if p["kind"] == "major"),
                      "subs": sum(1 for p in problems if p["kind"] == "sub"),
                      "subs_publishable": sum(1 for p in problems if p["kind"] == "sub" and p["status"]["publish"] == "publishable"),
                      "subs_with_solution": sum(1 for p in problems if p["kind"] == "sub" and p.get("solution")),
                      "subs_defective": sum(1 for p in problems if p["kind"] == "sub" and p["status"]["flags"].get("defective"))}}
    save_json(DATA / "catalog.json", cat)
    save_json(QA / "taxonomy_unmapped.json", {"generated_at": now_iso(), "cores": UNMAPPED["cores"].most_common(), "prerequisites": UNMAPPED["prerequisites"].most_common()})
    build_sqlite(cat, regions)
    print("catalog:", cat["counts"], "| lecture entries", len(lm["entries"]), "unmatched", len(lm["unmatched"]))

def build_sqlite(cat, regions):
    DB.mkdir(exist_ok=True)
    path = DB / "catalog.sqlite"
    if path.exists(): path.unlink()
    con = sqlite3.connect(path)
    con.executescript("""
    CREATE TABLE exams(exam_id TEXT PRIMARY KEY, school_code TEXT, year INT, round INT, display_name TEXT, problem_source_id TEXT, text_family TEXT, year_round_verified INT);
    CREATE TABLE problems(problem_id TEXT PRIMARY KEY, kind TEXT, exam_id TEXT, parent_id TEXT, number INT, display TEXT, order_index INT,
        year INT, round INT, official_answer TEXT, has_solution INT, publish_status TEXT, hold_reasons TEXT,
        primary_field TEXT, secondary_fields TEXT, cores TEXT, prerequisites TEXT, difficulty TEXT, est_minutes REAL, content_version INT, json TEXT);
    CREATE TABLE regions(region_id TEXT PRIMARY KEY, problem_id TEXT, role TEXT, exam_id TEXT, page_index INT, rect_pt TEXT, image_path TEXT, image_sha256 TEXT);
    CREATE TABLE tags(problem_id TEXT, tag_type TEXT, tag TEXT);
    """)
    for e in cat["exams"]:
        con.execute("INSERT INTO exams VALUES(?,?,?,?,?,?,?,?)", (e["exam_id"], e.get("school_code", "TOYO"), e["year"], e["round"], e["display_name"], e["problem_source_id"], e["text_family"], int(e.get("year_round_verified", False))))
    for p in cat["problems"]:
        an = p.get("analysis") or {}; le = p.get("learning") or {}
        con.execute("INSERT INTO problems VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (
            p["problem_id"], p["kind"], p["exam_id"], p.get("parent_id"), p["number"], p["display"], p["order_index"],
            p.get("year"), p.get("round"), (p.get("official_answer") or {}).get("raw"), int(bool(p.get("solution"))),
            (p.get("status") or {}).get("publish"), json.dumps((p.get("status") or {}).get("hold_reasons", []), ensure_ascii=False),
            an.get("primary_field"), json.dumps(an.get("secondary_fields", []), ensure_ascii=False), json.dumps(an.get("cores", []), ensure_ascii=False),
            json.dumps(an.get("prerequisites", []), ensure_ascii=False), le.get("difficulty"), le.get("est_minutes"), p["content_version"],
            json.dumps(p, ensure_ascii=False)))
        for t in an.get("cores", []): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "core_raw", t))
        for t in an.get("cores_canonical", []): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "core", t))
        for t in an.get("prereq_canonical", []): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "prereq_canonical", t))
        for t in an.get("secondary_fields", []): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "field", t))
        if an.get("primary_field"): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "field", an["primary_field"]))
        for t in an.get("prerequisites", []): con.execute("INSERT INTO tags VALUES(?,?,?)", (p["problem_id"], "prereq", t if isinstance(t, str) else t.get("skill", "")))
    for r in regions.values():
        con.execute("INSERT INTO regions VALUES(?,?,?,?,?,?,?,?)", (r["region_id"], r["problem_id"], r["role"], r["exam_id"], r["page_index"], json.dumps(r["rect_pt"]), r["image_path"], r["image_sha256"]))
    con.commit(); con.close()

if __name__ == "__main__":
    import json
    main()
