"""資料台帳 (data/sources.json)・試験台帳 (data/exams.json)・ページ役割 (data/pages.json) を作る。

- 入力は読み取り専用。再実行しても既存の exam 番号は変えない (追記のみ)。
- 年度・入試回はファイル名からは *仮* 推定し、表紙テキスト/目視で確認した結果を
  data/exam_verification.json (手動記入) から取り込む。
"""
from __future__ import annotations
import re, sys
from pathlib import Path
import fitz  # PyMuPDF
from common import *

JG_PAT = re.compile(r"女子学院算数-(mondai|kaito)(?: \((\d+)\))?\.pdf$")
TOYO_WEB_PAT = re.compile(r"^(\d{4})Math0(\d)(A?)\.pdf$")
ANSWER_SHEET_PAT = re.compile(r"解答")

def classify_source(name: str):
    """(school, kind, year, round, basis) を返す。year/round は仮推定 (None 可)。"""
    m = JG_PAT.search(name)
    if m:
        n = int(m.group(2) or 0)
        kind = "problem_booklet" if m.group(1) == "mondai" else "answer_sheet"
        return "JG", kind, 2026 - n, 1, "ファイル名の連番 (n) → 2026−n。表紙/解答末尾の年度表記と目視照合済み (2026-10-22)"
    m = TOYO_WEB_PAT.match(name)
    if m:
        kind = "answer_sheet" if m.group(3) else "problem_booklet"
        return "TOYO", kind, int(m.group(1)), int(m.group(2)), "学校サイトのファイル名 (yyyyMath0N[A].pdf)。表紙テキストで年度・回を確認"
    kind = "answer_sheet" if ANSWER_SHEET_PAT.search(name) else "problem_booklet"
    y, r = parse_year_round_from_name(name)
    return "TOYO", kind, y, r, "ファイル名から推定、表紙画像で目視確認 (2026-10-22)"

def page_role(pg: fitz.Page, idx: int, n: int, family: str, prev_roles: list[str]) -> tuple[str, str]:
    """(role, basis) を返す。family は抽出テキストの品質区分。prev_roles は同一冊子の先行ページの役割。"""
    text = pg.get_text()
    norm = re.sub(r"[\s\x03]+", "", text)
    nimg = len(pg.get_images())
    ndraw = len(pg.get_drawings())
    if family == "scan":
        # 女子学院: 問題用紙そのものに年度見出しがあり表紙は無い。4ページ構成の最終ページは解答用紙 (白紙)
        if n == 4 and idx == 3:
            return "answer_sheet_blank", "scan:4ページ構成の末尾 (目視確認)"
        return "problem", "scan:全ページ問題"
    if idx == 0:
        return "cover", "first_page"
    if "解答用紙" in norm:
        # 冊子末尾の解答用紙: 1枚目は未記入、2枚目は学校作成の正解入り (目視確認で確定)
        return ("official_answers" if "answer_sheet_blank" in prev_roles else "answer_sheet_blank"), "text_match:解答用紙"
    if "計算用紙" in norm or "ィ⟬⏝⣬" in norm:  # 後者は2022年度の文字化け形
        return "scratch", "text_match:計算用紙"
    if family == "outline":
        # 2025: 日本語はアウトライン化。PUA数字がページ番号程度しか無く描画がほぼ無いページは計算用紙
        if len(text.strip()) < 12 and ndraw < 5 and nimg == 0:
            return "scratch", "heuristic_outline(ページ番号のみ)"
        return "problem", "heuristic_outline"
    if len(norm) == 0 and nimg == 0 and ndraw == 0:
        return "blank", "empty"
    if len(norm) < 15 and nimg == 0:
        return "scratch_or_blank", "heuristic_short"
    return "problem", "heuristic_text"

def text_family(doc: fitz.Document) -> str:
    """抽出テキストの品質区分: readable / gid_garbled / outline / scan"""
    pg = doc[2] if len(doc) > 2 else doc[0]
    t = pg.get_text()
    if len(t.strip()) < 5 and len(pg.get_images()) >= 1:
        return "scan"
    pua = len(re.findall(r"[\ue000-\uf8ff]", t)); kana = len(re.findall(r"[ぁ-ん]", t)); cjk = len(re.findall(r"[一-龥]", t))
    if pua and pua > 3 * (kana + cjk):      # 本文がアウトライン化され、ルビ程度の文字しか残っていない (2025・2026)
        return "outline"
    if "㸦" in t or "ࡢ" in t:
        return "gid_garbled"
    if re.search(r"[ぁ-ん]", t):
        return "readable"
    return "unknown"

def cover_text(doc: fitz.Document) -> str:
    t = doc[0].get_text()
    return re.sub(r"\s+", " ", t).strip()[:200]

def main():
    sources = load_json(DATA / "sources.json", {"sources": []})
    by_path = {s["rel_path"]: s for s in sources["sources"]}
    exams = load_json(DATA / "exams.json", {"exams": []})
    verif = load_json(DATA / "exam_verification.json", {})
    pages_doc = load_json(DATA / "pages.json", {"pages": []})
    role_over = load_json(DATA / "page_role_overrides.json", {})

    pdfs = sorted(p for p in EXAM_PDF_DIR.iterdir() if p.suffix.lower() == ".pdf")
    for d in EXTRA_EXAM_PDF_DIRS:
        if d.exists():
            pdfs += sorted(p for p in d.iterdir() if p.suffix.lower() == ".pdf")
    ext = load_json(DATA / "external_refs.json", {"refs": []})
    web_meta = {}
    for r_ in ext.get("refs", []):
        for u in r_.get("files", []):
            web_meta[u.rsplit("/", 1)[-1]] = {"url": u, "confirmed_at": r_.get("confirmed_at"), "ref_id": r_.get("id")}
    new_sources = []
    for p in pdfs:
        relp = rel(p)
        sha = sha256_file(p)
        school, kind, y, r, basis = classify_source(p.name)
        doc = fitz.open(p)
        fam = text_family(doc)
        entry = by_path.get(relp, {})
        sid = entry.get("source_id") or f"SRC-{sha[:12]}"
        entry.update({
            "source_id": sid,
            "rel_path": relp,
            "file_name": p.name,
            "sha256": sha,
            "bytes": p.stat().st_size,
            "pages": len(doc),
            "page_size_pt": [round(doc[0].rect.width, 2), round(doc[0].rect.height, 2)],
            "rotation": doc[0].rotation,
            "kind": kind,
            "school_code": school,
            "school": SCHOOLS[school]["name"],
            "answer_source_kind": ("publisher" if school == "JG" else "school") if kind == "answer_sheet" else None,
            "year_from_name": y, "round_from_name": r, "year_round_basis": basis,
            "text_family": fam,
            "cover_text_excerpt": cover_text(doc),
            "in_scope": True,
            "origin": web_meta.get(p.name, {"url": None}) if p.name in web_meta else {"url": None, "note": "利用者提供の過去問フォルダ"},
            "ingested_at": entry.get("ingested_at") or now_iso(),
            "last_seen_at": now_iso(),
        })
        by_path[relp] = entry
        new_sources.append(entry)
    sources["sources"] = sorted(by_path.values(), key=lambda s: s["rel_path"])
    sources["generated_at"] = now_iso()
    sources["input_dir"] = rel(EXAM_PDF_DIR)
    save_json(DATA / "sources.json", sources)

    # --- 試験台帳: 問題冊子ごとに1試験。既存番号は維持し、新規は末尾に追加 (学校ごとに連番)。
    for e in exams["exams"]:
        e.setdefault("school_code", "TOYO")
    existing = {(e["school_code"], e["year"], e["round"]): e for e in exams["exams"]}
    booklets = [s for s in sources["sources"] if s["kind"] == "problem_booklet"]
    booklets.sort(key=lambda s: (s["school_code"], s["year_from_name"] or 0, s["round_from_name"] or 0))
    next_num = {}
    for sc in SCHOOLS:
        nums = [int(e["exam_id"].split("E")[-1]) for e in exams["exams"] if e["school_code"] == sc]
        next_num[sc] = 1 + max(nums or [0])
    for s in booklets:
        sc = s["school_code"]
        key = (sc, s["year_from_name"], s["round_from_name"])
        v = verif.get(s["source_id"], {})
        if key in existing:
            e = existing[key]
        else:
            e = {"exam_id": exam_id(next_num[sc], SCHOOLS[sc]["id_prefix"]), "school_code": sc, "year": key[1], "round": key[2]}
            next_num[sc] += 1
            exams["exams"].append(e); existing[key] = e
        single_round = (sc == "JG")
        e.update({
            "school": SCHOOLS[sc]["name"], "subject": "算数",
            "display_name": (f"女子学院 {key[1]}年度" if single_round else f"{key[1]}年度 第{key[2]}回"),
            "problem_source_id": s["source_id"],
            "answer_sheet_source_ids": [t["source_id"] for t in sources["sources"]
                                        if t["kind"] == "answer_sheet" and (t["school_code"], t["year_from_name"], t["round_from_name"]) == key],
            "answer_source_kind": "publisher" if sc == "JG" else "school",
            "text_family": s["text_family"],
            "year_round_basis": v.get("basis", s.get("year_round_basis", "filename_only(未確認)")),
            "year_round_verified": v.get("verified", s.get("year_round_basis", "").find("目視") >= 0),
            "verified_at": v.get("verified_at"),
            "verified_by": v.get("verified_by", "agent_visual"),
            "notes": v.get("notes"),
        })
    exams["exams"].sort(key=lambda e: (e["school_code"] != "TOYO", e["exam_id"]))
    exams["generated_at"] = now_iso()
    save_json(DATA / "exams.json", exams)

    # --- ページ役割
    pages = []
    for e in exams["exams"]:
        s = next(t for t in sources["sources"] if t["source_id"] == e["problem_source_id"])
        doc = fitz.open(ROOT / s["rel_path"])
        prev_roles = []
        for i, pg in enumerate(doc):
            role, basis = page_role(pg, i, len(doc), s["text_family"], prev_roles)
            ov = role_over.get(f"{e['exam_id']}:{i}")
            if ov:
                role, basis = ov["role"], "manual_override:" + ov.get("reason", "")
            prev_roles.append(role)
            printed = None
            m = re.search(r"[－\-㸫]\s*(\d+)\s*[－\-㸫]", pg.get_text())
            if m:
                printed = m.group(1)
            pages.append({"exam_id": e["exam_id"], "source_id": s["source_id"], "page_index": i,
                          "page_display": i + 1, "printed_page": printed, "role": role, "role_basis": basis,
                          "width_pt": round(pg.rect.width, 2), "height_pt": round(pg.rect.height, 2),
                          "rotation": pg.rotation, "cropbox": [round(v, 2) for v in pg.cropbox],
                          "n_images": len(pg.get_images()), "n_drawings": len(pg.get_drawings()),
                          "n_text_chars": len(pg.get_text().strip())})
    save_json(DATA / "pages.json", {"generated_at": now_iso(), "pages": pages})

    # --- 塾解説・授業ノートの台帳
    lec = {"generated_at": now_iso(), "dir": rel(LECTURE_DIR), "files": []}
    for p in sorted((LECTURE_DIR / "out").glob("*.json")):
        lec["files"].append({"rel_path": rel(p), "sha256": sha256_file(p), "bytes": p.stat().st_size})
    for p in [LECTURE_DIR / "README.md", LECTURE_DIR / "schema.py", LECTURE_DIR / "exam_urls.txt"]:
        if p.exists():
            lec["files"].append({"rel_path": rel(p), "sha256": sha256_file(p), "bytes": p.stat().st_size})
    lec["frames_dirs"] = len(list((LECTURE_DIR / "out" / "frames").glob("*")))
    save_json(DATA / "lecture_sources.json", lec)
    tp = TEACHING_PDF
    tdoc = fitz.open(tp)
    save_json(DATA / "teaching_notes_source.json", {
        "rel_path": rel(tp), "sha256": sha256_file(tp), "bytes": tp.stat().st_size, "pages": len(tdoc),
        "page_size_pt": [round(tdoc[0].rect.width, 2), round(tdoc[0].rect.height, 2)],
        "headings": [{"page_index": i, "text": re.sub(r"\s+", " ", pg.get_text()).strip()} for i, pg in enumerate(tdoc)],
        "generated_at": now_iso()})

    print(f"sources: {len(sources['sources'])} (booklets {len(booklets)}, answer sheets "
          f"{sum(1 for s in sources['sources'] if s['kind']=='answer_sheet')}, other-school "
          f"{sum(1 for s in sources['sources'] if s['kind']=='other_school')})")
    print(f"exams: {len(exams['exams'])}; pages: {len(pages)}; lecture files: {len(lec['files'])}")

if __name__ == "__main__":
    main()
