"""豊島岡: 表紙 (1 ページ目) の『注意事項 4. 円周率は 3.14 とし、答えが比になる場合は、最も簡単な整数の比で答えなさい。』を、
その条件に依存する大問の共通部の先頭に複製する (data/segmentation_overrides/TOYO-E00xx.json の add_regions, lead=True)。
対象の大問は data/toyo_cover_note_targets.json (静的リスト。選定の根拠はそのファイルの _doc)。行の位置は layout (PDF のテキスト位置) から求める。
segment.py の前に実行する。冪等 (前回の複製を消して作り直す)。"""
import json, re
from common import *

def lines(layout):
    pg = layout["pages"][0]
    sp = sorted(pg["spans"], key=lambda s: (round(s["bbox"][1]), s["bbox"][0]))
    out = []
    for s in sp:
        b = s["bbox"]
        for L in out:
            if abs(L["y0"] - b[1]) < 3.5 and abs(L["y1"] - b[3]) < 4:
                L["x0"] = min(L["x0"], b[0]); L["x1"] = max(L["x1"], b[2]); L["y0"] = min(L["y0"], b[1]); L["y1"] = max(L["y1"], b[3]); L["t"] += s.get("text", ""); break
        else:
            out.append({"y0": b[1], "y1": b[3], "x0": b[0], "x1": b[2], "t": s.get("text", "")})
    return sorted(out, key=lambda l: l["y0"])

def note_rect(layout):
    """『４．円周率は…』の行 (折り返しがあれば 2 行目まで) の矩形 (pt)。見つからなければ None。"""
    L = [l for l in lines(layout) if l["y0"] > 400]
    idx = next((i for i, l in enumerate(L) if "円周率" in l["t"] or "3.14" in l["t"]), None)
    if idx is None: return None
    st = L[idx]; end = st
    if idx + 1 < len(L) and L[idx + 1]["x0"] > st["x0"] + 12 and L[idx + 1]["y0"] - st["y1"] < 14: end = L[idx + 1]   # 字下げされた続きの行
    return [round(min(st["x0"], end["x0"]) - 3, 1), round(st["y0"] - 3, 1), round(max(st["x1"], end["x1"]) + 3, 1), round(end["y1"] + 3, 1)]

def main():
    tg = load_json(DATA / "toyo_cover_note_targets.json")["targets"]
    by_exam = {}
    for t in tg: by_exam.setdefault(t.rsplit("-Q", 1)[0], []).append(t)
    n = 0
    for e in load_json(DATA / "exams.json")["exams"]:
        eid = e["exam_id"]
        if e.get("school_code", "TOYO") != "TOYO": continue
        path = DATA / "segmentation_overrides" / f"{eid}.json"
        ov = load_json(path, {})
        old = ov.get("add_regions", [])
        keep = [r for r in old if not r.get("cover_note")]
        new = []
        if eid in by_exam:
            rect = note_rect(load_json(DATA / "layout" / f"{eid}.json"))
            if rect is None:
                print("!! 表紙の注意事項が見つからない:", eid); continue
            for mid in by_exam[eid]:
                new.append({"region_id": f"{mid}-stem-p01-note", "problem_id": mid, "role": "stem", "page_index": 0, "rect": rect,
                            "content_rect": [rect[0] + 3, rect[1] + 3, rect[2] - 3, rect[3] - 3], "lead": True, "cover_note": True,
                            "note": "表紙の注意事項 4 (円周率は 3.14・答えが比になる場合は最も簡単な整数の比) の複製: この大問の本文には書かれていない共通の条件 (scripts/toyo_cover_notes.py)"})
        if keep != old or new:
            if new and "表紙の注意事項" not in ov.get("notes", ""):
                ov["notes"] = (ov.get("notes", "") + " / " if ov.get("notes") else "") + "表紙の注意事項 4 (円周率 3.14・比の答え方) を、それに依存する大問 (" + ", ".join(r["problem_id"].split("-")[-1] for r in new) + ") の共通部の先頭に複製 (toyo_cover_notes.py, 2026-10-23 目視)"
            ov["add_regions"] = keep + new
            if not ov["add_regions"]: ov.pop("add_regions")
            save_json(path, ov); n += len(new)
        elif path.exists() and not ov.get("add_regions") and old != keep:
            pass
    print("toyo cover notes:", n, "regions in", len(by_exam), "exams")

if __name__ == "__main__":
    main()
