"""女子学院: ページ単位の候補シート (1 ページ 1 画像, 150dpi)。左余白の候補塊に番号と OCR 文字を付け、y 定規 (50pt) を描く。"""
import sys
from PIL import Image, ImageDraw, ImageFont
from common import *
out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
only = set(sys.argv[2:]) or None
exams = [e for e in load_json(DATA / "exams.json")["exams"] if e["school_code"] == "JG" and (not only or e["exam_id"] in only)]
pages = load_json(DATA / "pages.json")["pages"]
sources = {s["source_id"]: s for s in load_json(DATA / "sources.json")["sources"]}
import fitz
DPI = 150; k = DPI / 72
try:
    font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 22)
except Exception:
    font = ImageFont.load_default()
for e in exams:
    L = load_json(DATA / "layout" / f"{e['exam_id']}.json")
    doc = fitz.open(ROOT / sources[e["problem_source_id"]]["rel_path"])
    for p in [p for p in pages if p["exam_id"] == e["exam_id"] and p["role"] == "problem"]:
        pi = p["page_index"]; page = L["pages"][pi]
        pix = doc[pi].get_pixmap(dpi=DPI, alpha=False); im = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
        d = ImageDraw.Draw(im)
        for yy in range(50, int(page["height"]), 50):
            d.line([(0, yy * k), (im.width, yy * k)], fill=(200, 200, 255), width=1)
            d.text((im.width - 70, yy * k - 12), str(yy), fill=(0, 0, 255), font=font)
        for i, c in enumerate(page.get("margin_candidates", [])):
            x0, y0, x1, y1 = [v * k for v in c["bbox"]]
            d.rectangle([x0 - 3, y0 - 3, x1 + 3, y1 + 3], outline=(220, 0, 0), width=3)
            label = f"{i}:{c['text'][:5]}|{c['bbox'][1]:.0f}"
            d.rectangle([x1 + 6, y0 - 2, x1 + 6 + 11 * len(label), y0 + 24], fill=(255, 240, 0))
            d.text((x1 + 8, y0), label, fill=(0, 0, 0), font=font)
        im.save(out / f"{e['exam_id']}_p{pi+1}.png")
print("done")
