"""女子学院 (スキャン) の手動マーカー指定を助ける診断シート: 各問題ページに左余白の候補塊を番号付きで描き、候補一覧を出力する。"""
import json, sys, os
from PIL import Image, ImageDraw
from common import *
out = Path(sys.argv[1]); out.mkdir(parents=True, exist_ok=True)
exams = [e for e in load_json(DATA / "exams.json")["exams"] if e["school_code"] == "JG"]
pages = load_json(DATA / "pages.json")["pages"]
DPI = 110; k = DPI / 72
lines = []
for e in exams:
    L = load_json(DATA / "layout" / f"{e['exam_id']}.json")
    ps = [p for p in pages if p["exam_id"] == e["exam_id"] and p["role"] == "problem"]
    ims = []
    for p in ps:
        pi = p["page_index"]; page = L["pages"][pi]
        im = Image.open(ASSETS / "pages" / e["exam_id"] / f"p{pi+1:02d}.png")
        im = im.resize((int(page["width"] * k), int(page["height"] * k)))
        d = ImageDraw.Draw(im)
        lines.append(f"## {e['exam_id']} p{pi+1}")
        for i, c in enumerate(page.get("margin_candidates", [])):
            x0, y0, x1, y1 = [v * k for v in c["bbox"]]
            d.rectangle([x0 - 2, y0 - 2, x1 + 2, y1 + 2], outline=(220, 0, 0), width=2)
            d.rectangle([x1 + 4, y0 - 1, x1 + 40, y0 + 13], fill=(255, 230, 0)); d.text((x1 + 6, y0), f"{i}:{c['text'][:4]}", fill=(0, 0, 0))
            lines.append(f"  {i}: y={c['bbox'][1]:.0f} h={c['bbox'][3]-c['bbox'][1]:.0f} x={c['bbox'][0]:.0f} w={c['bbox'][2]-c['bbox'][0]:.0f} ocr={c['text']!r}")
        # y ruler
        for yy in range(100, int(page["height"]), 100):
            d.line([(0, yy * k), (12, yy * k)], fill=(0, 0, 255), width=2); d.text((2, yy * k - 12), str(yy), fill=(0, 0, 255))
        ims.append((pi + 1, im))
    w = max(im.size[0] for _, im in ims); h = max(im.size[1] for _, im in ims)
    sheet = Image.new("RGB", (len(ims) * (w + 8), h + 18), "white"); d = ImageDraw.Draw(sheet)
    for j, (pd, im) in enumerate(ims):
        sheet.paste(im, (j * (w + 8), 18)); d.text((j * (w + 8) + 4, 2), f"{e['exam_id']} p{pd}", fill=(200, 0, 0))
    sheet.save(out / f"{e['exam_id']}.png")
(out / "candidates.txt").write_text("\n".join(lines), encoding="utf-8")
print("done", len(exams))
