"""自動セグメンテーション。

問題ページのテキスト位置情報から 大問(箱数字) / 小問 (1)(2)… のマーカーを検出し、
各小問・各大問共通部(stem)の矩形領域を決めて data/segmentation/<exam_id>.json に書く。
抽出テキストはマーカー検出にだけ使い、内容の確定には使わない (原本画像で目視確認する)。

手動修正: data/segmentation_overrides/<exam_id>.json
  {"pages": {"<page_index>": {"markers": [{"kind":"sub"|"box","n":2,"y":123.4}, ...]}},   # そのページの検出結果を置換
   "regions": {"<region_id>": {"rect":[x0,y0,x1,y1]}},                                     # 矩形の上書き
   "remove_regions": ["<region_id>"], "add_regions": [ {...region...} ], "notes": "..."}
"""
from __future__ import annotations
import re, sys, collections
from common import *

X_LEFT, PAD, PAGE_NO_Y = 30.0, 3.0, 655.0

def decode_text(text: str, font: str) -> str:
    out = []
    for c in text:
        o = ord(c)
        if 0xF000 <= o < 0xF100:
            out.append(chr(o - 0xF000))
        elif font.startswith("SukenRoman") and 0x08 <= o <= 0x3D:
            out.append(chr(o + 0x1D))      # 数字・大文字 (GID = code - 0x1D)
        elif font.startswith("SukenKigou") and 0x08 <= o <= 0x3D:
            out.append({0x08: "×", 0x09: "÷", 0x0E: "+", 0x10: "−"}.get(o, "〓"))  # 記号フォント (不明は〓)
        elif c == "㸦": out.append("（")
        elif c == "㸧": out.append("）")
        elif c == "㸫": out.append("－")
        elif c == "\x03": out.append(" ")
        else: out.append(c)
    s = "".join(out)
    return s.translate(str.maketrans("０１２３４５６７８９", "0123456789"))

def page_lines(spans):
    """y 近傍でスパンを行にまとめる。"""
    spans = sorted(spans, key=lambda s: (round((s["bbox"][1] + s["bbox"][3]) / 2), s["bbox"][0]))
    lines = []
    for s in spans:
        yc = (s["bbox"][1] + s["bbox"][3]) / 2
        if lines and abs(lines[-1]["yc"] - yc) <= 4.0:
            lines[-1]["spans"].append(s)
        else:
            lines.append({"yc": yc, "spans": [s]})
    for l in lines:
        l["spans"].sort(key=lambda s: s["bbox"][0])
        l["text"] = "".join(decode_text(s["text"], s["font"]) for s in l["spans"])
        l["x0"] = min(s["bbox"][0] for s in l["spans"]); l["y0"] = min(s["bbox"][1] for s in l["spans"])
        l["y1"] = max(s["bbox"][3] for s in l["spans"])
    return lines

SUB_RE = re.compile(r"^\s*[（(]\s*([1-9])\s*[）)]")
BOX_RE = re.compile(r"^\s*([1-6])(?:$|[\s　])")

def ocr_lines(spans, ytol=5.0):
    """OCR トークンを行にまとめ、隣接トークンを結合したテキストと先頭 x を返す。"""
    spans = sorted(spans, key=lambda s: ((s["bbox"][1] + s["bbox"][3]) / 2, s["bbox"][0]))
    lines = []
    for s in spans:
        yc = (s["bbox"][1] + s["bbox"][3]) / 2
        if lines and abs(lines[-1]["yc"] - yc) <= ytol:
            lines[-1]["spans"].append(s); lines[-1]["yc"] = (lines[-1]["yc"] + yc) / 2
        else:
            lines.append({"yc": yc, "spans": [s]})
    for l in lines:
        l["spans"].sort(key=lambda s: s["bbox"][0])
        l["x0"] = l["spans"][0]["bbox"][0]; l["y0"] = min(s["bbox"][1] for s in l["spans"]); l["y1"] = max(s["bbox"][3] for s in l["spans"])
        l["text"] = "".join(s["text"] for s in l["spans"])
    return lines

SCAN_SUB_RE = re.compile(r"^[\(（\[\{@©]?\s*([0-9ilI]?)\s*[\)）\]\}]")   # '(1)', '2)', '@)' (=(1) の誤読) など
SCAN_BOX_RE = re.compile(r"^([1-9])\s*[.．,:;]?$")

def detect_markers_scan(page, W):
    """スキャンページ (女子学院): 左余白のインク塊 (margin_candidates, 細かく分かれる) を y でまとめて問題番号にする。
    '(1)' は '(' '1' ')' の 2〜3 塊に分かれ、太字の大問番号 '1.' は幅 8pt 以上の 1 塊になる。
    判定: 塊が 2 個以上 or 括弧を含む → 小問 (数字は中央の塊の OCR)、1 塊で幅 ≥ 7 → 大問。番号は hint とし、呼び出し側で出現順に割り当てる。
    根拠: 番号は左余白 (x ≤ 42pt) にあり本文は 45pt 以上から始まる (2005〜2026 で共通)。"""
    H = page.get("height", 1032.0)
    cands = [c for c in page.get("margin_candidates", []) if 58 <= c["bbox"][1] <= H * 0.91]
    cands.sort(key=lambda c: (c["bbox"][1], c["bbox"][0]))
    groups = []
    for c in cands:
        yc = (c["bbox"][1] + c["bbox"][3]) / 2
        if groups and abs(groups[-1]["yc"] - yc) <= 4.5 and c["bbox"][0] - groups[-1]["x1"] < 12:
            groups[-1]["items"].append(c); groups[-1]["x1"] = max(groups[-1]["x1"], c["bbox"][2])
            groups[-1]["yc"] = (groups[-1]["yc"] + yc) / 2
        else:
            groups.append({"yc": yc, "items": [c], "x1": c["bbox"][2]})
    marks = []
    for g in groups:
        it = sorted(g["items"], key=lambda c: c["bbox"][0])
        x0 = min(c["bbox"][0] for c in it); x1 = max(c["bbox"][2] for c in it)
        y0 = min(c["bbox"][1] for c in it); y1 = max(c["bbox"][3] for c in it)
        texts = [c["text"] for c in it]
        joined = "".join(texts)
        has_paren = any(("(" in t) or (")" in t) for t in texts)
        digits = re.sub(r"[^0-9]", "", joined)
        if len(it) >= 2 or has_paren or (x1 - x0) >= 13:
            kind = "sub"
        elif (x1 - x0) >= 7:
            kind = "box"
        else:
            continue   # 小さすぎる単独塊 (ノイズ)
        hint = int(digits[0]) if digits else None
        marks.append((kind, hint, y0, y1, x0, joined or "?"))
    marks.sort(key=lambda m: m[2])
    return marks

def scan_column_right(page):
    """計算欄との仕切り線 (縦の細長い塊) があればその x を返す。無ければ None。"""
    W, H = page.get("width", 728.0), page.get("height", 1032.0)
    for d in page.get("lines", []) + page["drawings"]:
        x0, y0, x1, y1 = d
        if (x1 - x0) < 8 and (y1 - y0) > H * 0.35 and 0.45 * W < x0 < 0.78 * W:
            return x0
    return None

def scan_divider_fit(page):
    """傾いてスキャンされた計算欄の仕切り線: 細い縦の断片 (幅<9pt) が 0.5〜0.72W に縦 0.4H 以上並ぶとき、直線 x = a*y + b を最小二乗で当てはめて返す。"""
    W, H = page.get("width", 728.0), page.get("height", 1032.0)
    frags = [d for d in page["drawings"] if (d[2] - d[0]) < 9 and (d[3] - d[1]) >= 6 and 0.5 * W < d[0] < 0.72 * W]
    if len(frags) < 6: return None
    xs = [(d[0] + d[2]) / 2 for d in frags]; ys = [(d[1] + d[3]) / 2 for d in frags]
    if max(ys) - min(ys) < 0.4 * H: return None
    n = len(xs); mx, my = sum(xs) / n, sum(ys) / n
    syy = sum((y - my) ** 2 for y in ys)
    if syy == 0: return None
    a = sum((y - my) * (x - mx) for x, y in zip(xs, ys)) / syy; b = mx - a * my
    inl = [(x, y) for x, y in zip(xs, ys) if abs(x - (a * y + b)) < 5]
    if len(inl) < 6 or abs(a) > 0.05: return None
    return (a, b)

def detect_markers(page, family):
    """ページ内のマーカー候補 [(kind, n, y0, y1, x0, text)] を返す (順序検証は呼び出し側)。
    行の再構成に頼らず、'（' スパンの右隣の数字スパン、または '（1）' 1スパンを直接探す。"""
    spans = sorted(page["spans"], key=lambda s: (s["bbox"][1], s["bbox"][0]))
    marks, used_digit = [], set()
    pn_top = page_number_top(page)
    if family == "scan":
        return detect_markers_scan(page, page.get("width", 728.0))
    if family == "outline":
        for s in spans:
            x0, y0, x1, y1 = s["bbox"]
            ts = decode_text(s["text"], s["font"]).strip()
            if y0 < pn_top and 50.0 <= x0 <= 62.0 and re.fullmatch(r"[1-9]", ts) and (x1 - x0) < 9:
                marks.append(("sub", int(ts), y0, y1, x0, ts))
            m = re.match(r"^\s*[（(]\s*([1-9])\s*[）)]", ts)
            if m and x0 < 66 and y0 < pn_top:
                marks.append(("sub", int(m.group(1)), y0, y1, x0, ts[:10]))
        marks.sort(key=lambda m: m[2]); return marks
    for i, s in enumerate(spans):
        x0, y0, x1, y1 = s["bbox"]
        if y0 > PAGE_NO_Y or x0 > 66 or y0 >= pn_top: continue
        t = decode_text(s["text"], s["font"]); ts = t.strip()
        m = re.match(r"^\s*[（(]\s*([1-9])\s*[）)]", t)
        if m:
            marks.append(("sub", int(m.group(1)), y0, y1, x0, t[:20])); continue
        if ts in ("（", "("):
            for j, s2 in enumerate(spans):
                b = s2["bbox"]
                if x1 - 2 <= b[0] <= x1 + 12 and b[1] < y1 and b[3] > y0:
                    t2 = decode_text(s2["text"], s2["font"]).strip()
                    if re.fullmatch(r"[1-9]", t2):
                        marks.append(("sub", int(t2), min(y0, b[1]), max(y1, b[3]), x0, "（" + t2 + "）")); used_digit.add(j); break
    for j, s in enumerate(spans):
        if j in used_digit: continue
        x0, y0, x1, y1 = s["bbox"]
        if y0 >= 60 or x0 >= 60: continue
        t = decode_text(s["text"], s["font"]); ts = t.strip()
        if re.fullmatch(r"[1-6]", ts) or re.match(r"^[1-6][\s\u3000]", t):
            marks.append(("box", int(ts[0]), y0, y1, x0, ts[:10]))
    marks.sort(key=lambda m: m[2])
    return marks

PAGE_NO_RE = re.compile(r"^[-－—―\s]*\d{1,2}[-－—―\s]*$")

def page_number_top(page) -> float:
    """ページ番号行の上端 y を返す (無ければ PAGE_NO_Y)。
    中央帯 (x 150-380) にある '－3－' 形式の候補のうち、その下に本文テキストが無い最下行を採用する。"""
    spans = page["spans"]
    cands = []
    for s in spans:
        t = decode_text(s["text"], s["font"]).strip()
        x0, y0, x1, y1 = s["bbox"]
        if y0 >= 560 and x0 >= 150 and x1 <= 380 and (PAGE_NO_RE.fullmatch(t) or t in ("－", "-", "—", "―")):
            cands.append(s)
    for c in sorted(cands, key=lambda s: -s["bbox"][1]):
        cy = (c["bbox"][1] + c["bbox"][3]) / 2
        below = [s for s in spans if s not in cands and decode_text(s["text"], s["font"]).strip()
                 and (s["bbox"][1] + s["bbox"][3]) / 2 > cy + 3]
        if not below:
            same = [s for s in cands if abs((s["bbox"][1] + s["bbox"][3]) / 2 - cy) <= 4]
            return min(s["bbox"][1] for s in same) - 2
    return PAGE_NO_Y

def is_page_number(span, pn_top):
    return span["bbox"][1] >= pn_top

def content_elements(page, family):
    els = []
    if family == "scan":
        W, H = page.get("width", 728.0), page.get("height", 1032.0)
        for d in page["drawings"]:
            x0, y0, x1, y1 = d
            w, h = x1 - x0, y1 - y0
            if y0 > H * 0.915: continue                      # 下端: ページ番号・受験番号欄
            if y1 < 62: continue                             # 上端: 年度・学校名の見出し
            if x0 > W * 0.84 and w < 75 and h < 75: continue  # 右端の得点・小計・合計の枠
            if w < 8 and h > 200: continue                   # 計算欄との仕切り線
            if w < 2 and h < 2: continue
            els.append(("draw", d))
        return els
    pn_top = page_number_top(page)
    for s in page["spans"]:
        t = decode_text(s["text"], s["font"]).strip()
        if not t: continue
        if s["bbox"][1] >= pn_top: continue  # ページ番号行
        els.append(("text", s["bbox"]))
    for im in page["images"]:
        b = im["bbox"]
        if b[3] - b[1] < 1 or b[2] - b[0] < 1: continue
        els.append(("image", b))
    for d in page["drawings"]:
        if d[1] >= pn_top - 3 and d[3] - d[1] < 3: continue
        if d[3] - d[1] < 0.5 and d[2] - d[0] < 0.5: continue
        els.append(("draw", d))
    return els

def trim_rect(rect, content, blobs):
    """余白付きの切り出し矩形から、隣の領域のインク (内容矩形の外側にあって余白帯に入り込む塊・仕切り線・得点枠) を外す。
    内容矩形は変えない (余白だけを縮める)。内容矩形に重なる塊は『隣の領域のもの』と判断できないので触らない。
    小さな点・ごみ (幅も高さも 8pt 未満で細い横線でもないもの) は無視する。内容の外接矩形は膨張した塊の外接なので、実際のインクより外側にある。"""
    x0, y0, x1, y1 = rect; cx0, cy0, cx1, cy1 = content
    for f in blobs:
        fx0, fy0, fx1, fy1 = f
        w, h = fx1 - fx0, fy1 - fy0
        if not (w >= 8 or h >= 8 or (w >= 20 and h <= 4)): continue
        if min(fx1, x1) - max(fx0, x0) > 1.0:                    # 横に重なる → 上下の隣
            if fy1 <= cy0 + 0.3 and fy1 > y0: y0 = max(y0, fy1 + 0.6)
            if fy0 >= cy1 - 0.3 and fy0 < y1: y1 = min(y1, fy0 - 0.6)
        if min(fy1, y1) - max(fy0, y0) > 1.0:                    # 縦に重なる → 左右の隣
            if fx1 <= cx0 + 0.3 and fx1 > x0: x0 = max(x0, fx1 + 0.6)
            if fx0 >= cx1 - 0.3 and fx0 < x1: x1 = min(x1, fx0 - 0.6)
    x0 = min(x0, cx0 - 0.5); y0 = min(y0, cy0 - 0.5); x1 = max(x1, cx1 + 0.5); y1 = max(y1, cy1 + 0.5)
    return [round(x0, 2), round(y0, 2), round(x1, 2), round(y1, 2)]

def segment_scan_regions(exam, layout, events, problem_pages, warnings, official, override, W):
    """スキャン (女子学院) 用の領域割当。
    - マーカー (手動指定 data/jg_marker_spec.txt → overrides.pages[pi].markers) の y で帯 (band) を切り、帯に 40% 以上掛かるインク塊で矩形を決める
      (内容矩形はインク塊の外接矩形: 空白行・右欄の得点枠を含めない)。
    - ページ毎の上下限 y_top / y_bottom (既定 58 / 982pt: 見出し・受験番号欄を除外)、右端 x_right (仕切り線 or 指定 or W-14)。
    - figs: 複数小問に共通の図 (手動矩形) を大問共通部 (stem) として切り出し、図の y 範囲に掛かる小問帯は図の左で切る (帯内の塊が全て図の左にある場合のみ)。
    - splits: 小問帯を y で上下に分け、下側を『後続小問に共通の説明』(stem, applies_from_sub = 次の小問) にする。
    - cont: ページ先頭が前ページの問題の続き。"""
    eid = exam["exam_id"]
    regions, problems = [], {}
    def ensure_major(qn):
        mid = major_id(eid, qn)
        problems.setdefault(mid, {"problem_id": mid, "kind": "major", "number": qn, "printed": f"{qn}.", "subs": []})
        return mid
    def ensure_sub(qn, sn):
        mid = ensure_major(qn); sid = sub_id(eid, qn, sn)
        if sid not in problems:
            problems[sid] = {"problem_id": sid, "kind": "sub", "parent_id": mid, "number": sn, "printed": f"({sn})"}
            problems[mid]["subs"].append(sid)
        return sid
    last = None  # (qn, sn or 0)
    pending_copies = []   # (page_index, {q, rect}): spec の copy (別の大問の先頭行・1 ページ冒頭の注意書きの複製)
    for pi, page_ev in events:
        page = layout["pages"][pi]
        H = page.get("height", 1032.0)
        pov = override.get("pages", {}).get(str(pi), {}) or {}
        for c in pov.get("copies", []): pending_copies.append((pi, c))
        y_top = float(pov.get("y_top", 58.0))
        y_bottom = float(pov.get("y_bottom", 982.0 if H > 1000 else H * 0.95))
        xr = pov.get("x_right") or scan_column_right(page)   # 計算欄の仕切り線 (塊が無い帯の既定右端と、仕切り線の残骸の除去に使う)
        fit = scan_divider_fit(page) if not xr else None     # 傾いた仕切り線 (直線除去で消えず断片が残る)
        if fit:
            xr = min(fit[0] * y + fit[1] for y in (y_top, y_bottom)) - 1
        x_right = (xr - 4) if xr else W - 14
        x_left = 18.0
        figs = [dict(f) for f in pov.get("figs", [])]
        joins = [dict(j) for j in pov.get("joins", [])]
        splits = list(pov.get("splits", []))
        def in_fig(d):
            cx, cy = (d[0] + d[2]) / 2, (d[1] + d[3]) / 2
            return any(f["rect"][0] - 2 <= cx <= f["rect"][2] + 2 and f["rect"][1] - 2 <= cy <= f["rect"][3] + 2 for f in figs + joins)
        # 右端の得点・小計・合計の枠 (右余白に孤立した幅 65〜110pt, 高さ 50〜85pt の矩形) と、その中の文字 (得・点・番号・小計・合計) を除く。
        # 図の一部 (例: 2026 p3 図1 の右半分) を誤って除かないよう、左 30pt 以内に同じ高さの他の塊がある矩形は枠とみなさない。
        frames = page.get("frames", [])   # layout.py (ink_blobs) で検出
        page_blobs = [list(b) for b in page["drawings"]] + [list(b) for b in page.get("lines", [])]   # 隣の領域のインクの判定用 (仕切り線・得点枠の中身を含む全部)
        def in_frame(d):
            cx, cy = (d[0] + d[2]) / 2, (d[1] + d[3]) / 2
            return any(f[0] - 2 <= cx <= f[2] + 2 and f[1] - 2 <= cy <= f[3] + 2 for f in frames)
        els = []
        for d in page["drawings"]:
            x0, y0, x1, y1 = d; w, h = x1 - x0, y1 - y0; cy = (y0 + y1) / 2
            if cy > y_bottom or cy < y_top: continue           # 見出し・受験番号欄・ページ番号 (中心で判定)
            if in_frame(d): continue                            # 得点枠とその中身
            if x0 > W * 0.8 and y0 < 75: continue               # 右上の校名スタンプ
            if x0 > W * 0.9 and w <= 40 and h <= 16 and y0 > H * 0.93: continue   # 右下のページ番号 (−1− など)
            if w < 8 and h > 40: continue                       # 計算欄との仕切り線の除去漏れ (細い縦線)
            if w < 9 and xr and abs(x0 - xr) <= 14: continue    # 仕切り線の残骸 (仕切り線の x の近くの細い塊)
            if w < 9 and fit and abs((x0 + x1) / 2 - (fit[0] * cy + fit[1])) <= 10: continue   # 傾いた仕切り線の断片
            if w * h <= 36 or (h <= 3.5 and w <= 24) or (w <= 3.5 and h <= 24): continue   # スキャンのごみ (点・短い線分)
            if w >= 0.9 * W: continue                           # ページ幅の塊 (用紙の端)
            if in_fig(d): continue
            els.append(d)
        ordered = sorted([e for e in page_ev if e[1] in ("sub", "box")], key=lambda e: e[3])
        segs = []  # (kind, qn, sn, y_top_band, y_bot_band, extra)
        if not ordered:
            if last is None:
                warnings.append(f"p{pi+1}: マーカー無しページ (先頭)")
                continue
            segs.append(("cont", last[0], last[1], y_top, y_bottom, {}))
        else:
            # 帯の境界はマーカー上端の 7pt 上: 前の行 (中心はマーカーの約 10pt 上) は前の帯、分数の分子 (中心は約 4pt 上) はこの帯に入る
            GAP = 7.0
            if pov.get("cont") and last is not None:
                segs.append(("cont", last[0], last[1], y_top, ordered[0][3] - GAP, {}))
            for i, e in enumerate(ordered):
                yt = max(y_top, e[3] - GAP)
                yb = (ordered[i + 1][3] - GAP) if i + 1 < len(ordered) else y_bottom
                segs.append((e[1], e[5], e[2] if e[1] == "sub" else 0, yt, yb, {}))
        # splits: 小問帯を分割し、下側を後続小問共通の説明にする
        out = []
        for kind, qn, sn, yt, yb, extra in segs:
            sp = [x for x in splits if yt < x["y"] < yb and x.get("q") == qn]
            if sp and kind == "sub":
                y = float(sp[0]["y"])
                out.append((kind, qn, sn, yt, y - 2, extra))
                out.append(("stem2", qn, sn, y, yb, {"applies_from_sub": sn + 1}))
            else:
                if sp: warnings.append(f"p{pi+1}: split y={sp[0]['y']} は小問帯に掛からない")
                out.append((kind, qn, sn, yt, yb, extra))
        segs = out
        page_regions = []
        for kind, qn, sn, yt, yb, extra in segs:
            inside = []
            for d in els:
                ov = min(d[3], yb) - max(d[1], yt)
                h = d[3] - d[1]
                if ov <= 0: continue
                if h >= 0.28 * H:
                    if ov >= 10: inside.append([d[0], max(d[1], yt), d[2], min(d[3], yb)])   # 縦に長い塊 (括弧など) は帯で切る
                elif ov >= 0.5 * h:
                    inside.append(list(d))   # 半分以上が帯に入る塊はその帯の内容として全体を含める (図・解答欄が帯の上下にはみ出しても切らない)
            xr_band = W - 14   # 内容の右端は塊で決める (仕切り線は制限にしない: 問題が仕切り線を越えて右欄まで広がる年度がある)
            if kind != "box":
                for f in figs:
                    fx0, fy0, fx1, fy1 = f["rect"]
                    ov = min(fy1, yb) - max(fy0, yt)
                    if ov > 4 and all(d[2] <= fx0 - 2 for d in inside):
                        xr_band = min(xr_band, fx0 - 4)
            inside = [d for d in inside if d[0] < xr_band + 2]
            sig = [d for d in inside if (d[3] - d[1]) >= 4]   # 細い横線の断片 (解答欄の上辺など) は判定から除く
            if kind == "box" and (not sig or (all(d[2] < 70 for d in sig) and len(sig) <= 2)):
                ensure_major(qn); last = (qn, 0)
                continue   # 大問番号だけで共通の本文が無い (小問が番号の直後から始まる) → 共通部の領域は作らない
            if inside:
                cx0 = min(d[0] for d in inside); cy0 = min(d[1] for d in inside)
                cx1 = max(d[2] for d in inside); cy1 = max(d[3] for d in inside)
                content = [round(max(x_left, cx0), 2), round(cy0, 2), round(min(xr_band + 2, cx1), 2), round(cy1, 2)]
                rect = [round(max(14.0, cx0 - 4), 2), round(max(y_top - 4, cy0 - 3), 2), round(min(W - 14, cx1 + 4), 2), round(min(y_bottom + 8, cy1 + 3), 2)]
                rect = trim_rect(rect, [cx0, cy0, cx1, cy1], page_blobs)
            else:
                xr0 = min(xr_band, x_right)
                content = [x_left, round(yt, 2), xr0, round(yb, 2)]
                rect = [round(max(14.0, x_left - 4), 2), round(yt - 2, 2), round(min(W - 14, xr0 + 3), 2), round(yb + 2, 2)]
                warnings.append(f"p{pi+1}: 帯 {kind} 大問{qn} 小問{sn} y={yt:.0f}-{yb:.0f} にインク塊が無い (帯全体を使用)")
            if kind == "box":
                ensure_major(qn)
                last = (qn, 0)
                page_regions.append(dict(problem_id=major_id(eid, qn), role="stem", page_index=pi, rect=rect, content_rect=content))
            elif kind == "sub":
                sid = ensure_sub(qn, sn)
                page_regions.append(dict(problem_id=sid, role="main", page_index=pi, rect=rect, content_rect=content))
                last = (qn, sn)
            elif kind == "stem2":
                page_regions.append(dict(problem_id=ensure_major(qn), role="stem", page_index=pi, rect=rect, content_rect=content,
                                         applies_from_sub=extra["applies_from_sub"], manual=True, note=f"小問({sn})の後に置かれた後続小問共通の説明 (split)"))
            else:  # cont
                if sn == 0:
                    page_regions.append(dict(problem_id=ensure_major(qn), role="stem", page_index=pi, rect=rect, content_rect=content, note="前ページの大問共通部の続き (要確認)", needs_check=True))
                else:
                    page_regions.append(dict(problem_id=ensure_sub(qn, sn), role="continuation", page_index=pi, rect=rect, content_rect=content, note="前ページの小問の続き (要確認)", needs_check=True))
        # joins: 小問の内容矩形に手動矩形を合併する (帯の境界をまたぐ図やラベルをその小問に含める)
        for j in joins:
            sid = sub_id(eid, j["q"], j["s"])
            r = next((r for r in page_regions if r["problem_id"] == sid and r["role"] == "main"), None)
            if not r:
                warnings.append(f"p{pi+1}: join 対象の小問領域 {sid} がこのページに無い"); continue
            jr = [float(v) for v in j["rect"]]
            c = r["content_rect"]
            c = [min(c[0], jr[0]), min(c[1], jr[1]), max(c[2], jr[2]), max(c[3], jr[3])]
            r["content_rect"] = [round(v, 2) for v in c]
            r["rect"] = trim_rect([round(max(14.0, c[0] - 4), 2), round(max(y_top - 4, c[1] - 3), 2), round(min(W - 14, c[2] + 4), 2), round(min(y_bottom + 8, c[3] + 3), 2)], c, page_blobs)
            r["manual"] = True; r["note"] = "手動矩形 (join) を合併"
        # 上下に隣接する領域の余白が重なる場合は内容矩形の間の中点で切る (隣の行の一部が写り込まないように)
        prs = sorted(page_regions, key=lambda r: r["content_rect"][1])
        for i, a in enumerate(prs):
            for b in prs[i + 1:]:
                ax0, ay0, ax1, ay1 = a["content_rect"]; bx0, by0, bx1, by1 = b["content_rect"]
                if min(ax1, bx1) - max(ax0, bx0) <= 0: continue      # 横に並ぶ領域 (図と本文) は対象外
                if ay1 > by0: continue                               # 内容自体が重なる場合はそのまま
                if a["rect"][3] > b["rect"][1]:
                    mid = round((ay1 + by0) / 2, 2)
                    a["rect"][3] = max(round(ay1 + 0.5, 2), min(a["rect"][3], mid))
                    b["rect"][1] = min(round(by0 - 0.5, 2), max(b["rect"][1], mid))
        # clips: 領域の切り出し矩形 (rect) を手動で置き換える (内容矩形は変えない)。s=0 は大問の共通部 (stem)
        for c in pov.get("clips", []):
            sid = sub_id(eid, c["q"], c["s"]) if c["s"] else None
            tgt = next((r for r in page_regions if (sid and r["problem_id"] == sid and r["role"] == "main")
                        or (not sid and r["problem_id"] == major_id(eid, c["q"]) and r["role"] == "stem" and "applies_from_sub" not in r)), None)
            if tgt is None and c["s"] == 1:   # 小問の無い大問 (後で S01 の main になる共通部)
                tgt = next((r for r in page_regions if r["problem_id"] == major_id(eid, c["q"]) and r["role"] == "stem"), None)
            if tgt is None: warnings.append(f"p{pi+1}: clip{c['q']}.{c['s']} の対象領域が無い"); continue
            tgt["rect"] = [round(float(v), 2) for v in c["rect"]]; tgt["manual"] = True
            tgt["note"] = ((tgt.get("note") + " / ") if tgt.get("note") else "") + "切り出し矩形を手動指定 (clip): 隣の行の断片を除く"
        # figs: 手動矩形の図 — 大問共通 (stem) または特定の小問 (main) の直後に挿入 (複数あるときは指定順を保つ)
        n_inserted = collections.Counter()
        for f in figs:
            q = f["q"]; mid = ensure_major(q)
            fr = [round(float(v), 2) for v in f["rect"]]
            if f.get("s"):
                sid = ensure_sub(q, f["s"])
                reg = dict(problem_id=sid, role="main", page_index=pi, rect=fr, content_rect=list(fr), manual=True,
                           note="小問の図 (手動矩形, data/jg_marker_spec.txt の fig)", region_id=f"{sid}-main-p{pi+1:02d}-fig")
                idx = next((i for i, r in enumerate(page_regions) if r["problem_id"] == sid and r["role"] == "main"), None)
                key = ("s", sid)
            else:
                reg = dict(problem_id=mid, role="stem", page_index=pi, rect=fr, content_rect=list(fr), manual=True,
                           note="複数小問に共通の図 (手動矩形, data/jg_marker_spec.txt の fig)", region_id=f"{mid}-stem-p{pi+1:02d}-fig")
                idx = next((i for i, r in enumerate(page_regions) if r["problem_id"] == mid and r["role"] == "stem"), None)
                key = ("m", mid)
            if idx is None: page_regions.append(reg)
            else: page_regions.insert(idx + 1 + n_inserted[key], reg)
            n_inserted[key] += 1
        regions.extend(page_regions)
    # copy: 別の大問の先頭行・1 ページ冒頭の注意書きを、対象の大問の共通部の先頭に複製する (元の領域と重なってよい。lead=True で表示順の先頭)
    n_copy = collections.Counter()
    for pi, c in pending_copies:
        mid = ensure_major(c["q"])
        x0, y0, x1, y1 = [float(v) for v in c["rect"]]
        n_copy[(mid, pi)] += 1
        suffix = "note" if n_copy[(mid, pi)] == 1 else f"note-{n_copy[(mid, pi)]}"
        regions.append(dict(problem_id=mid, role="stem", page_index=pi,
                            rect=[round(max(8.0, x0 - 4), 2), round(max(0.0, y0 - 2.5), 2), round(min(W - 14, x1 + 2.5), 2), round(y1 + 2.5, 2)],
                            content_rect=[round(x0, 2), round(y0, 2), round(x1, 2), round(y1, 2)], manual=True, lead=True,
                            note="共通の指示文・注意書きの複製 (data/jg_marker_spec.txt の copy): 原本では別の大問の先頭または 1 ページ冒頭にある行",
                            region_id=f"{mid}-stem-p{pi+1:02d}-{suffix}"))
    for r in regions:
        if "region_id" not in r:
            r["region_id"] = f"{r['problem_id']}-{r['role']}-p{r['page_index']+1:02d}"
    seen = {}
    for r in regions:
        seen[r["region_id"]] = seen.get(r["region_id"], 0) + 1
        if seen[r["region_id"]] > 1: r["region_id"] += f"-{seen[r['region_id']]}"
    # 小問の無い大問 → 大問全体を S01 に
    for mid, pr in list(problems.items()):
        if pr["kind"] == "major" and not pr["subs"]:
            sid = sub_id(eid, pr["number"], 1)
            problems[sid] = {"problem_id": sid, "kind": "sub", "parent_id": mid, "number": 1, "printed": "(なし: 大問全体)", "single": True}
            pr["subs"].append(sid)
            for r in regions:
                if r["problem_id"] == mid and r["role"] == "stem" and not r.get("lead"):   # copy 領域 (注意書き・共通の指示) は共通部のまま
                    r["problem_id"] = sid; r["role"] = "main"; r["note"] = (r.get("note", "") + " / " if r.get("note") else "") + "小問の無い大問 (全体が1問)"
                    r["region_id"] = r["region_id"].replace(mid + "-stem", sid + "-main")
    # overrides (矩形上書き・削除・追加・flags)
    for rid, o in override.get("regions", {}).items():
        for r in regions:
            if r["region_id"] == rid:
                r.update({k: v for k, v in o.items()}); r["manual"] = True
    rm = set(override.get("remove_regions", []))
    regions = [r for r in regions if r["region_id"] not in rm]
    for o in override.get("add_regions", []):
        o["manual"] = True; o.setdefault("content_rect", o["rect"]); regions.append(o)
    for pid, fl in override.get("problem_flags", {}).items():
        if pid in problems: problems[pid]["flags"] = fl
    off_rec = official.get(eid, {}); off = off_rec.get("answers", {})
    exp = {k: len(v) for k, v in off.items()}
    got = {f"Q{p['number']:02d}": len(p["subs"]) for p in problems.values() if p["kind"] == "major"}
    if off_rec.get("needs_check"):
        warnings.append("解答 (出版社・自動解読) は構成が不確実なため照合は参考値")
    if exp != got:
        warnings.append(f"小問構成が解答と不一致: 検出 {got} / 解答 {exp}")
    for r in regions:
        problems[r["problem_id"]].setdefault("region_ids", []).append(r["region_id"])
    rmap = {r["region_id"]: r for r in regions}
    for p in problems.values():
        if p.get("region_ids"): p["region_ids"].sort(key=lambda rid: 0 if rmap[rid].get("lead") else 1)   # copy 領域 (注意書き・共通指示) は先頭
    for p in problems.values():
        if p["kind"] == "sub":
            p["stem_region_ids"] = [rid for rid in problems[p["parent_id"]].get("region_ids", []) if rmap[rid].get("applies_from_sub", 1) <= p["number"]]
    return {"exam_id": eid, "text_family": "scan", "generated_at": now_iso(), "segmentation_version": 3,
            "coord_system": "PyMuPDF page coords (pt, origin top-left)", "page_width": W,
            "problems": list(problems.values()), "regions": regions, "warnings": warnings,
            "structure_matches_official": exp == got, "override_applied": bool(override)}

def pad_rects(regions, W, pad_top=5.0, pad_bot=5.0):
    xl = X_LEFT if W < 600 else 24.0
    by_page = {}
    for r in regions:
        by_page.setdefault(r["page_index"], []).append(r)
    for rs in by_page.values():
        rs.sort(key=lambda r: r["content_rect"][1])
        for i, r in enumerate(rs):
            x0, y0, x1, y1 = r["content_rect"]
            top, bot = y0 - pad_top, y1 + pad_bot
            if i > 0:
                prev_bot = rs[i - 1]["content_rect"][3]
                if top < prev_bot + 1:
                    top = max(y0 - 1.5, (prev_bot + y0) / 2)
            if i + 1 < len(rs):
                next_top = rs[i + 1]["content_rect"][1]
                if bot > next_top - 1:
                    bot = min(y1 + 1.5, (y1 + next_top) / 2)
            r["rect"] = [round(max(xl, x0 - 6), 2), round(max(20, top), 2), round(min(W - 20, x1 + 8), 2), round(bot, 2)]

def bbox_of(els):
    if not els: return None
    return [min(e[1][0] for e in els), min(e[1][1] for e in els), max(e[1][2] for e in els), max(e[1][3] for e in els)]

def segment_exam(exam, pages_roles, layout, official, override):
    fam = exam["text_family"]
    eid = exam["exam_id"]
    W = layout["pages"][0]["width"]
    problem_pages = [p for p in pages_roles if p["role"] == "problem"]
    warnings = []
    # --- 1. マーカー検出 + 順序検証 (大問は (1) の再開で切り替え。箱数字は検証に使う)
    q, s = 0, 0
    box_open = False
    events = []  # (page_index, kind, n, y0, y1, q, s)
    for p in problem_pages:
        pi = p["page_index"]; page = layout["pages"][pi]
        q_before, s_before = q, s
        ov = override.get("pages", {}).get(str(pi))
        if ov and "markers" in ov:
            marks = [(m["kind"], m["n"], m["y"], m.get("y1", m["y"] + 12), m.get("x", 42), "manual") for m in ov["markers"]]
            marks.sort(key=lambda m: m[2])
        else:
            marks = detect_markers(page, fam)
        page_ev = []
        if fam == "scan" and not (ov and "markers" in ov):
            # OCR の数字は信用せず出現順に番号を振る: box → 次の大問 (digit が q+1 でなければ警告), sub → s+1 (hint が 1 なら新しい大問)
            fixed = []
            for kind, n, y0, y1, x0, t in marks:
                if kind == "box":
                    if n != q + 1 and n != q:
                        warnings.append(f"p{pi+1}: 大問番号の OCR 値 {n} が順序 (次は {q+1}) と合わない → 順序を優先 text={t!r}")
                    fixed.append(("box", q + 1 if n != q else q, y0, y1, x0, t)); q_tmp = q + 1 if n != q else q
                    # 以降の sub の基準を更新するため一時的に q を進める
                    q, s = (q + 1 if n != q else q), 0
                else:
                    if n == 1 and s > 0:
                        q, s = q + 1, 1
                    else:
                        s += 1
                        if n is not None and n != s:
                            warnings.append(f"p{pi+1}: 小問番号の OCR 値 ({n}) を出現順 ({s}) に置換 text={t!r}")
                    fixed.append(("sub", s, y0, y1, x0, t))
            # 状態を巻き戻して通常の処理に渡す (q, s は fixed の処理で再計算される)
            q, s = q_before, s_before
            marks = fixed
        for kind, n, y0, y1, x0, t in marks:
            if kind == "box":
                if n == q + 1 and (s > 0 or q == 0 or fam == "scan"):
                    q, s, box_open = n, 0, True; page_ev.append((pi, "box", n, y0, y1, q, s))
                elif n == q and s == 0:
                    pass  # 同じ大問の箱が再検出 (重複) → 無視
                else:
                    warnings.append(f"p{pi+1}: 箱数字 {n} が順序に合わない (現在 大問{q} 小問{s}) y={y0:.0f} text={t!r}")
            else:
                if n == 1 and box_open:
                    s, box_open = 1, False; page_ev.append((pi, "sub", 1, y0, y1, q, s))
                elif n == 1:
                    q, s, box_open = q + 1, 1, False; page_ev.append((pi, "sub", 1, y0, y1, q, s))
                    page_ev.append((pi, "newq", q, y0, y1, q, 0))
                elif n == s + 1 and s > 0:
                    s = n; page_ev.append((pi, "sub", n, y0, y1, q, s))
                else:
                    warnings.append(f"p{pi+1}: 小問マーカー ({n}) が順序に合わない (現在 大問{q} 小問{s}) y={y0:.0f} text={t!r}")
        if not page_ev:
            warnings.append(f"p{pi+1}: マーカー未検出の問題ページ (大問{q} 小問{s} の続き or 次の大問の共通部と推定)")
        events.append((pi, page_ev))
    # --- 2. 領域割当
    regions = []
    problems = {}
    if fam == "scan":
        return segment_scan_regions(exam, layout, events, problem_pages, warnings, official, override, W)
    def ensure_major(qn):
        mid = major_id(eid, qn)
        problems.setdefault(mid, {"problem_id": mid, "kind": "major", "number": qn, "printed": str(qn), "subs": []})
        return mid
    def ensure_sub(qn, sn):
        mid = ensure_major(qn); sid = sub_id(eid, qn, sn)
        if sid not in problems:
            problems[sid] = {"problem_id": sid, "kind": "sub", "parent_id": mid, "number": sn, "printed": f"({sn})"}
            problems[mid]["subs"].append(sid)
        return sid
    cur_q, cur_s = 0, 0
    pending_header_pages = []  # マーカー無しページ (次の大問共通部に回す候補)
    for pi, page_ev in events:
        page = layout["pages"][pi]
        els = content_elements(page, fam)
        subs = [e for e in page_ev if e[1] == "sub"]
        boxes = [e for e in page_ev if e[1] == "box"]
        newq = [e for e in page_ev if e[1] == "newq"]
        if not page_ev:
            pending_header_pages.append((pi, els)); continue
        # 先頭セグメント (最初のマーカーより上)
        cuts = sorted(set([e[3] for e in subs] + [e[3] for e in boxes]))
        first = min(page_ev, key=lambda e: e[3])
        first_y = first[3]
        top_els = [e for e in els if (e[1][1] + e[1][3]) / 2 < first_y - PAD and e[1][3] < first[3] - 2]
        top_els = [e for e in top_els if not (e[1][3] >= first[3] + (-2 if e[0] == "text" else 1) and e[1][1] >= first[3] - 40)]
        if first[1] == "box":
            if top_els and fam != "scan":
                warnings.append(f"p{pi+1}: 箱数字より上に要素 {len(top_els)} 個 (無視)")
            header_q = first[5]
        elif first[1] == "sub" and first[2] == 1:
            header_q = first[5]
            # マーカー無しページ + 上部要素を共通部に
            for hpi, hels in pending_header_pages:
                b = bbox_of(hels)
                if b: regions.append(dict(problem_id=ensure_major(header_q), role="stem", page_index=hpi, rect=b, note="マーカー無しページ全体を共通部と推定(要確認)", needs_check=True))
            pending_header_pages = []
            b = bbox_of(top_els)
            if b: regions.append(dict(problem_id=ensure_major(header_q), role="stem", page_index=pi, rect=b))
        else:  # (k>1) で始まるページ: 直前の小問の続き
            qn, sn = first[5], first[2] - 1
            for hpi, hels in pending_header_pages:
                b = bbox_of(hels)
                if b: regions.append(dict(problem_id=ensure_sub(qn, sn), role="continuation", page_index=hpi, rect=b, note="マーカー無しページ全体を前小問の続きと推定(要確認)", needs_check=True))
            pending_header_pages = []
            b = bbox_of(top_els)
            if b: regions.append(dict(problem_id=ensure_sub(qn, sn), role="continuation", page_index=pi, rect=b, note="ページ先頭の続き部分(要確認)", needs_check=True))
        # 箱数字が中段にある場合 (1ページに2大問) も扱えるよう、マーカー順に区間を切る
        ordered = sorted([e for e in page_ev if e[1] in ("sub", "box")], key=lambda e: e[3])
        for i, e in enumerate(ordered):
            y_top = e[3] - PAD
            y_bot = ordered[i + 1][3] - PAD if i + 1 < len(ordered) else 10_000
            nxt = ordered[i + 1] if i + 1 < len(ordered) else None
            def touches(el, mk):
                """要素がマーカー行に掛かるか: テキスト(ルビ)は2pt上まで許容, 図形は実際に重なる場合のみ"""
                tol = -2 if el[0] == "text" else 1
                return el[1][3] >= mk[3] + tol and el[1][1] >= mk[3] - 40 and el[1][1] < mk[4]
            def belongs(el):
                yc = (el[1][1] + el[1][3]) / 2
                if nxt is not None and touches(el, nxt):
                    return False            # 次マーカー行に掛かるルビ・枠 → 次のセグメント
                if touches(el, e):
                    return True             # 自分のマーカー行に掛かる要素
                return y_top <= yc < y_bot
            seg = [el for el in els if belongs(el)]
            b = bbox_of(seg)
            if e[1] == "box":
                # 箱数字〜次マーカーまで = 共通部 (大問1,2 では「次の各問いに答えなさい。」のみ)
                ensure_major(e[5])
                if b: regions.append(dict(problem_id=major_id(eid, e[5]), role="stem", page_index=pi, rect=b))
            else:
                sid = ensure_sub(e[5], e[2])
                if b: regions.append(dict(problem_id=sid, role="main", page_index=pi, rect=b))
                else: warnings.append(f"p{pi+1}: 小問 ({e[2]}) の内容要素が見つからない")
    if pending_header_pages:
        for hpi, hels in pending_header_pages:
            warnings.append(f"p{hpi+1}: 末尾のマーカー無しページを割当できず (最後の小問の続き?)")
    # --- 2b. 小問マーカーの無い大問 (女子学院の 1 問完結型) は、大問全体を小問 S01 として扱う
    for mid, pr in list(problems.items()):
        if pr["kind"] == "major" and not pr["subs"]:
            sid = sub_id(eid, pr["number"], 1)
            problems[sid] = {"problem_id": sid, "kind": "sub", "parent_id": mid, "number": 1, "printed": "(なし: 大問全体)", "single": True}
            pr["subs"].append(sid)
            for r in regions:
                if r["problem_id"] == mid and r["role"] == "stem":
                    r["problem_id"] = sid; r["role"] = "main"; r["note"] = (r.get("note") or "") + " 小問の無い大問 (全体が1問)"
    # --- 3. 矩形の整形 (余白付与, 横幅は本文幅に統一; 隣接領域と重ならないよう余白をクランプ)
    for r in regions:
        r["content_rect"] = [round(v, 2) for v in r["rect"]]
        r["region_id"] = f"{r['problem_id']}-{r['role']}-p{r['page_index']+1:02d}"
    pad_rects(regions, W)
    # 同一IDの重複 (同ページに同役割が2つ) には連番
    seen = {}
    for r in regions:
        seen[r["region_id"]] = seen.get(r["region_id"], 0) + 1
        if seen[r["region_id"]] > 1:
            r["region_id"] += f"-{seen[r['region_id']]}"
    # overrides: figure_to_stem — 小問本文の下にある図を大問共通部へ分離
    for rid in override.get("figure_to_stem", []):
        r = next((r for r in regions if r["region_id"] == rid), None)
        if not r:
            warnings.append(f"figure_to_stem: 領域 {rid} が無い"); continue
        page = layout["pages"][r["page_index"]]
        x0, y0, x1, y1 = r["rect"]
        els = [el for el in content_elements(page, fam) if y0 <= (el[1][1] + el[1][3]) / 2 <= y1]
        figs = [el for el in els if el[0] != "text"]
        texts = [el for el in els if el[0] == "text"]
        if not figs:
            warnings.append(f"figure_to_stem: {rid} に図要素が無い"); continue
        # 小問本文の最終行 = 図の最上端より上にある最も下のテキスト
        fig_top = min(el[1][1] for el in figs)
        # 図の上端より上に本文が無い (図が本文と同じ高さ) 場合は横方向で切れないので警告
        body = [el for el in texts if el[1][3] <= fig_top + 2]
        if not body:
            warnings.append(f"figure_to_stem: {rid} 本文と図が縦に分離できない (手動矩形が必要)"); continue
        body_bottom = max(el[1][3] for el in body)
        fig_els = [el for el in els if (el[1][1] + el[1][3]) / 2 > body_bottom]
        fb = bbox_of(fig_els)
        bb = bbox_of(body)
        r["content_rect"] = [bb[0], bb[1], bb[2], round(body_bottom, 2)]
        r["rect"] = [x0, y0, x1, round(body_bottom + 5, 2)]; r["manual"] = True; r["note"] = "図を共通部へ分離"
        pid = problems[r["problem_id"]]["parent_id"]
        regions.append(dict(problem_id=pid, role="stem", page_index=r["page_index"], content_rect=[round(v, 2) for v in fb],
                            rect=[round(max(X_LEFT, fb[0] - 6), 2), round(fb[1] - 5, 2), round(min(W - 20, fb[2] + 8), 2), round(fb[3] + 5, 2)],
                            region_id=f"{pid}-stem-p{r['page_index']+1:02d}-fig", manual=True, note="小問の下に置かれた大問共通の図"))
    # overrides: split_region — 領域を at_y で上下に分け、下側を別役割 (例: 後続小問に共通の注記) にする
    for sp in override.get("split_region", []):
        r = next((r for r in regions if r["region_id"] == sp["region_id"]), None)
        if not r:
            warnings.append(f"split_region: 領域 {sp['region_id']} が無い"); continue
        page = layout["pages"][r["page_index"]]
        x0, y0, x1, y1 = r["content_rect"]
        els = [el for el in content_elements(page, fam) if y0 - 1 <= (el[1][1] + el[1][3]) / 2 <= y1 + 1]
        up = [el for el in els if (el[1][1] + el[1][3]) / 2 < sp["at_y"]]
        lo = [el for el in els if (el[1][1] + el[1][3]) / 2 >= sp["at_y"]]
        if not up or not lo:
            warnings.append(f"split_region: {sp['region_id']} を y={sp['at_y']} で分割できない"); continue
        ub, lb = bbox_of(up), bbox_of(lo)
        r["content_rect"] = [round(v, 2) for v in ub]; r["manual"] = True
        lower = dict(sp.get("lower", {}))
        role = lower.pop("role", "stem")
        pid = problems[r["problem_id"]]["parent_id"] if role == "stem" and problems[r["problem_id"]]["kind"] == "sub" else r["problem_id"]
        regions.append(dict(problem_id=pid, role=role, page_index=r["page_index"], content_rect=[round(v, 2) for v in lb],
                            region_id=f"{sp['region_id']}-split", manual=True, **lower))
    # overrides: rect 上書き / 削除 / 追加
    for rid, o in override.get("regions", {}).items():
        for r in regions:
            if r["region_id"] == rid:
                r.update({k: v for k, v in o.items()}); r["manual"] = True
    rm = set(override.get("remove_regions", []))
    regions = [r for r in regions if r["region_id"] not in rm]
    for o in override.get("add_regions", []):
        o["manual"] = True; o.setdefault("content_rect", o["rect"]); regions.append(o)
    pad_rects([r for r in regions if not r.get("lead")], W)   # lead (表紙の注意事項の複製) は指定の rect をそのまま使う
    for r in regions:
        if "rect" not in r:
            r["rect"] = r["content_rect"]
    for pid, fl in override.get("problem_flags", {}).items():
        if pid in problems:
            problems[pid]["flags"] = fl
        else:
            warnings.append(f"problem_flags: {pid} が無い")
    # --- 4. 公式解答の構成と照合
    off_rec = official.get(eid, {})
    off = off_rec.get("answers", {})
    exp = {k: len(v) for k, v in off.items()}
    if off_rec.get("needs_check"):
        warnings.append("公式解答 (出版社・自動解読) は構成が不確実なため照合は参考値")
    got = {f"Q{p['number']:02d}": len(p["subs"]) for p in problems.values() if p["kind"] == "major"}
    if exp != got:
        warnings.append(f"小問構成が公式解答と不一致: 検出 {got} / 公式 {exp}")
    # 問題ごとの領域参照
    for r in regions:
        problems[r["problem_id"]].setdefault("region_ids", []).append(r["region_id"])
        if r["role"] == "stem" and r["rect"][3] - r["rect"][1] < 30 and problems[r["problem_id"]]["number"] <= 2:
            r["trivial"] = True  # 「次の各問いに答えなさい。」のみ
    rmap = {r["region_id"]: r for r in regions}
    for p in problems.values():
        if p.get("region_ids"): p["region_ids"].sort(key=lambda rid: 0 if rmap[rid].get("lead") else 1)   # 注意書きの複製 (lead) は先頭
    for p in problems.values():
        if p["kind"] == "sub":
            p["stem_region_ids"] = [rid for rid in problems[p["parent_id"]].get("region_ids", [])
                                    if rmap[rid].get("applies_from_sub", 1) <= p["number"]]
    return {"exam_id": eid, "text_family": fam, "generated_at": now_iso(), "segmentation_version": 1,
            "coord_system": "PyMuPDF page coords (pt, origin top-left)", "page_width": W,
            "problems": list(problems.values()), "regions": regions, "warnings": warnings,
            "structure_matches_official": exp == got, "override_applied": bool(override)}

def main(only=None):
    exams = load_json(DATA / "exams.json")["exams"]
    pages = load_json(DATA / "pages.json")["pages"]
    official = load_official()
    report = []
    for e in exams:
        if only and e["exam_id"] not in only: continue
        layout = load_json(DATA / "layout" / f"{e['exam_id']}.json")
        pr = [p for p in pages if p["exam_id"] == e["exam_id"]]
        override = load_json(DATA / "segmentation_overrides" / f"{e['exam_id']}.json", {})
        seg = segment_exam(e, pr, layout, official, override)
        save_json(DATA / "segmentation" / f"{e['exam_id']}.json", seg)
        nmaj = sum(1 for p in seg["problems"] if p["kind"] == "major"); nsub = sum(1 for p in seg["problems"] if p["kind"] == "sub")
        line = f"{e['exam_id']} {e['display_name']}: 大問{nmaj} 小問{nsub} 領域{len(seg['regions'])} 公式一致={seg['structure_matches_official']} 警告{len(seg['warnings'])}"
        print(line); report.append(line)
        for w in seg["warnings"]: print("    !", w)
    (QA / "segmentation_report.txt").write_text("\n".join(report), encoding="utf-8")

if __name__ == "__main__":
    main(set(sys.argv[1:]) or None)
