"""各ページのテキストスパン・画像・描画の位置情報を data/layout/<exam_id>.json に保存する。
抽出テキストは *補助情報* であり原本より優先しない (2022年度は文字化け、2025年度はアウトライン)。
"""
from __future__ import annotations
import sys, re
import fitz
from common import *

def merge_rects(rects, gap=2.0):
    """近接する矩形をまとめる (描画要素のグルーピング用)。"""
    rects = [fitz.Rect(r) for r in rects if fitz.Rect(r).is_valid and not fitz.Rect(r).is_empty]
    changed = True
    while changed:
        changed = False
        out = []
        while rects:
            r = rects.pop()
            merged = False
            for i, o in enumerate(out):
                if (fitz.Rect(o) + (-gap, -gap, gap, gap)).intersects(r):
                    out[i] = fitz.Rect(o) | r; merged = True; changed = True; break
            if not merged:
                out.append(r)
        rects = out
    return [[round(v, 2) for v in r] for r in rects]

def page_layout(pg: fitz.Page):
    spans = []
    d = pg.get_text("dict")
    for b in d["blocks"]:
        if b["type"] != 0:
            continue
        for l in b["lines"]:
            for s in l["spans"]:
                if not s["text"].strip("\x03 　"):
                    continue
                spans.append({"bbox": [round(v, 2) for v in s["bbox"]], "font": s["font"],
                              "size": round(s["size"], 2), "text": s["text"]})
    images = []
    for info in pg.get_image_info():
        images.append({"bbox": [round(v, 2) for v in info["bbox"]], "w": info["width"], "h": info["height"]})
    draw_rects = []
    for dr in pg.get_drawings():
        r = dr.get("rect")
        if r is not None:
            draw_rects.append(r)
    drawings = merge_rects(draw_rects, gap=3.0)
    return {"spans": spans, "images": images, "drawings": drawings, "n_drawings_raw": len(draw_rects)}

OCR_DPI = 200

def ocr_spans(pg: fitz.Page):
    """スキャン画像ページ: tesseract (eng) の単語トークンを PDF 座標 (pt) のスパンに変換する。
    日本語辞書は未導入のため、数字・括弧・英字のみ信頼できる (マーカー検出と位置の補助に使う)。"""
    import subprocess, tempfile, os
    pix = pg.get_pixmap(dpi=OCR_DPI, alpha=False)
    with tempfile.TemporaryDirectory() as td:
        f = os.path.join(td, "p.png"); pix.save(f)
        out = subprocess.run(["tesseract", f, "-", "-l", "eng", "--psm", "11", "tsv"], capture_output=True, text=True).stdout
    k = 72.0 / OCR_DPI
    spans = []
    for row in out.strip().split("\n")[1:]:
        c = row.split("\t")
        if len(c) < 12 or not c[11].strip(): continue
        try:
            x, y, w, h, conf = int(c[6]), int(c[7]), int(c[8]), int(c[9]), float(c[10])
        except ValueError:
            continue
        spans.append({"bbox": [round(x * k, 2), round(y * k, 2), round((x + w) * k, 2), round((y + h) * k, 2)],
                      "font": "OCR", "size": round(h * k, 1), "text": c[11], "conf": conf})
    return spans

def margin_tokens(pg: fitz.Page, x1pt: float = 60.0, dpi: int = 400):
    """左余白 (0〜x1pt) だけを高解像度で OCR し、問題番号 '1.' '(1)' の候補を返す (数字・括弧・ピリオドに限定)。"""
    import subprocess, tempfile, os
    clip = fitz.Rect(0, 0, x1pt, pg.rect.height)
    pix = pg.get_pixmap(dpi=dpi, clip=clip, colorspace=fitz.csGRAY)
    with tempfile.TemporaryDirectory() as td:
        f = os.path.join(td, "s.png"); pix.save(f)
        out = subprocess.run(["tesseract", f, "-", "-l", "eng", "--psm", "11", "-c", "tessedit_char_whitelist=0123456789().", "tsv"], capture_output=True, text=True).stdout
    k = 72.0 / dpi; toks = []
    for row in out.strip().split("\n")[1:]:
        c = row.split("\t")
        if len(c) < 12 or not c[11].strip(): continue
        try:
            x, y, w, h, conf = int(c[6]), int(c[7]), int(c[8]), int(c[9]), float(c[10])
        except ValueError:
            continue
        toks.append({"bbox": [round(x * k, 2), round(y * k, 2), round((x + w) * k, 2), round((y + h) * k, 2)], "text": c[11], "conf": conf})
    return toks

def margin_candidates(pg: fitz.Page):
    """左余白 (x < 42pt) のインク塊を問題番号の候補とし、塊ごとに 400dpi・単語モードで OCR する。
    太字の大問番号 ('1.' '４．') は全面 OCR で落ちやすいため、塊単位で読む。戻り値: [{bbox, text, conf}]"""
    import subprocess, tempfile, os
    blobs = ink_blobs(pg, dpi=200, dilate_px=5)
    cands = [b for b in blobs if b[0] < 52 and b[2] < 76 and 4 <= (b[3] - b[1]) <= 28 and (b[2] - b[0]) <= 42 and b[1] > 58]
    out = []
    with tempfile.TemporaryDirectory() as td:
        for i, b in enumerate(cands):
            clip = fitz.Rect(max(0, b[0] - 3), b[1] - 3, b[2] + 3, b[3] + 3)
            pix = pg.get_pixmap(dpi=400, clip=clip, colorspace=fitz.csGRAY)
            f = os.path.join(td, f"c{i}.png"); pix.save(f)
            r = subprocess.run(["tesseract", f, "-", "-l", "eng", "--psm", "8", "-c", "tessedit_char_whitelist=0123456789().", "tsv"], capture_output=True, text=True).stdout
            text, conf = "", -1.0
            for row in r.strip().split("\n")[1:]:
                c = row.split("\t")
                if len(c) >= 12 and c[11].strip():
                    text += c[11].strip()
                    try: conf = max(conf, float(c[10]))
                    except ValueError: pass
            out.append({"bbox": [round(v, 2) for v in b], "text": text, "conf": conf})
    return out

def ink_blobs(pg: fitz.Page, dpi: int = 150, dilate_px: int = 13, return_lines: bool = False):
    """スキャン画像のインク領域を連結成分で矩形化し PDF 座標で返す (切り出し範囲の決定用)。
    1. 長い直線 (計算欄の仕切り線 ≥12%H, 用紙の端 ≥60%W) を除去 → 得点枠の検出 (右余白に孤立した矩形)。
    2. 傾いた仕切り線: 元画像の幅 ≤5px の縦筋 (長さ ≥12px) を Hough 変換でつなぎ、長さ ≥30%H・鉛直から 2° 以内の直線を除去
       (行どうしが線でつながるのを防ぐ。解答欄の縦辺・図の軸は短いので残る)。
    3. 横 dilate_px × 縦 3px で膨張して 1 行の文字をつなぎ、連結成分の外接矩形を返す。
    return_lines=True のとき (rects, line_rects, frames) を返す。"""
    import numpy as np, cv2
    pix = pg.get_pixmap(dpi=dpi, alpha=False, colorspace=fitz.csGRAY)
    img = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width)
    binar0 = (img < 160).astype(np.uint8) * 255
    k = 72.0 / dpi
    W, H = pix.width * k, pix.height * k
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (dilate_px, 3))
    def components(b):
        n, _, stats, _ = cv2.connectedComponentsWithStats(cv2.dilate(b, kernel, iterations=1), connectivity=8)
        out = []
        for i in range(1, n):
            x, y, w, h, area = stats[i]
            if area < 12: continue
            out.append([round(x * k, 2), round(y * k, 2), round((x + w) * k, 2), round((y + h) * k, 2)])
        return out
    # 1. 長い直線
    vk = cv2.getStructuringElement(cv2.MORPH_RECT, (1, max(60, int(pix.height * 0.12))))
    hk = cv2.getStructuringElement(cv2.MORPH_RECT, (max(60, int(pix.width * 0.6)), 1))
    lines = cv2.morphologyEx(binar0, cv2.MORPH_OPEN, vk) | cv2.morphologyEx(binar0, cv2.MORPH_OPEN, hk)
    # 仕切り線の両側 ±5pt (≈10px) も消す: スキャンで線の脇にできる細い影 (途切れた縦筋) が行と行をつなぐのを防ぐ
    binar = cv2.bitwise_and(binar0, cv2.bitwise_not(cv2.dilate(lines, cv2.getStructuringElement(cv2.MORPH_RECT, (21, 5)))))
    rects_a = components(binar)
    frames = []
    for f in rects_a:
        fw, fh = f[2] - f[0], f[3] - f[1]
        if not (f[0] >= W * 0.8 and f[2] >= W * 0.93 and 50 <= fh <= 85 and 65 <= fw <= 110): continue
        nb = [d for d in rects_a if d is not f and (d[2] - d[0]) > 8 and f[0] - 12 < d[2] <= f[0] + 2 and min(d[3], f[3]) - max(d[1], f[1]) > 10]
        if not nb: frames.append(f)
    # 縦の辺が薄くて閉じていない得点枠: 右余白の幅 65〜110pt の細い横線 (上辺・下辺) が 50〜85pt 離れて対になるもの
    edges = [d for d in rects_a if d[0] >= W * 0.8 and d[2] >= W * 0.93 and (d[3] - d[1]) <= 6 and 65 <= (d[2] - d[0]) <= 110]
    for a in edges:
        for b in edges:
            if b is a or not (50 <= b[1] - a[3] + 6 <= 85): continue
            if abs(a[0] - b[0]) > 8: continue
            f = [min(a[0], b[0]), a[1], max(a[2], b[2]), b[3]]
            if not any(abs(f[1] - g[1]) < 10 and abs(f[3] - g[3]) < 10 for g in frames):
                frames.append(f)
    # 2. 傾いた仕切り線 (元画像から検出: 直線除去で途切れた断片もつなぐ)
    short = cv2.morphologyEx(binar0, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 12)))
    wide = cv2.morphologyEx(short, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_RECT, (6, 1)))
    streak = cv2.bitwise_and(short, cv2.bitwise_not(wide))
    chain_rects = []
    mask = np.zeros_like(binar)
    segs = cv2.HoughLinesP(streak, 1, np.pi / 720, threshold=400, minLineLength=int(0.3 * pix.height), maxLineGap=60)
    if segs is not None:
        for x1, y1, x2, y2 in segs[:, 0, :]:
            if abs(int(x2) - int(x1)) > 0.035 * abs(int(y2) - int(y1)) + 2: continue   # 鉛直から 2° 以内
            cv2.line(mask, (int(x1), int(y1)), (int(x2), int(y2)), 255, 7)
            chain_rects.append([round(min(x1, x2) * k, 2), round(min(y1, y2) * k, 2), round((max(x1, x2) + 1) * k, 2), round((max(y1, y2) + 1) * k, 2)])
    mask = cv2.bitwise_and(mask, cv2.dilate(streak, cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))))
    n2, _, stats2, _ = cv2.connectedComponentsWithStats(lines, connectivity=8)
    line_rects = []
    for i in range(1, n2):
        x, y, w, h, area = stats2[i]
        line_rects.append([round(x * k, 2), round(y * k, 2), round((x + w) * k, 2), round((y + h) * k, 2)])
    line_rects += chain_rects
    # 仕切り線が途切れて検出された区間 (線が薄い・かすれた部分) にも細い筋が残り行と行をつなぐので、
    # 同じ x (±6pt) の縦線片をまとめ、その全区間で線の幅 ±1pt を消す (合計の長さが 30%H 以上のものだけ)
    vert = [r for r in line_rects if (r[2] - r[0]) < 8 and (r[3] - r[1]) >= 0.12 * H]
    clusters = []
    for r in sorted(vert, key=lambda r: r[0]):
        cx = (r[0] + r[2]) / 2
        for c in clusters:
            if abs(c["cx"] - cx) <= 6:
                c["x0"] = min(c["x0"], r[0]); c["x1"] = max(c["x1"], r[2]); c["y0"] = min(c["y0"], r[1]); c["y1"] = max(c["y1"], r[3]); break
        else:
            clusters.append({"cx": cx, "x0": r[0], "x1": r[2], "y0": r[1], "y1": r[3]})
    for c in clusters:
        if c["y1"] - c["y0"] < 0.3 * H: continue
        x0, x1 = int((c["x0"] - 1) / k), int((c["x1"] + 1) / k) + 1
        y0, y1 = int(c["y0"] / k), int(c["y1"] / k) + 1
        mask[y0:y1, max(0, x0):x1] = 255
    binar2 = cv2.bitwise_and(binar, cv2.bitwise_not(mask))
    rects = components(binar2)
    if return_lines:
        return rects, line_rects, frames
    return rects

def main(only=None):
    exams = load_json(DATA / "exams.json")["exams"]
    sources = {s["source_id"]: s for s in load_json(DATA / "sources.json")["sources"]}
    for e in exams:
        if only and e["exam_id"] not in only:
            continue
        s = sources[e["problem_source_id"]]
        outp = DATA / "layout" / f"{e['exam_id']}.json"
        old = load_json(outp)
        if old and old.get("sha256") == s["sha256"] and old.get("layout_version") == 20:
            continue
        doc = fitz.open(ROOT / s["rel_path"])
        pages = []
        for i, pg in enumerate(doc):
            if s["text_family"] == "scan":
                blobs, line_rects, frames = ink_blobs(pg, return_lines=True)
                pl = {"spans": ocr_spans(pg), "images": [], "drawings": blobs, "lines": line_rects, "frames": frames, "n_drawings_raw": 0, "margin_tokens": margin_tokens(pg), "margin_candidates": margin_candidates(pg),
                      "ocr": "tesseract eng psm11 (全面) + 左余白 60pt を 400dpi で数字限定 OCR", "ink": "cv2 connected components (100dpi, dilate 9px)"}
            else:
                pl = page_layout(pg)
            pl.update({"page_index": i, "width": round(pg.rect.width, 2), "height": round(pg.rect.height, 2)})
            pages.append(pl)
        save_json(outp, {"exam_id": e["exam_id"], "source_id": s["source_id"], "sha256": s["sha256"],
                         "layout_version": 20, "coord_system": "PyMuPDF page coords (pt, origin top-left, y down)",
                         "generated_at": now_iso(), "pages": pages})
        print("layout", e["exam_id"], len(pages), "pages")

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