"""
Figure-crop script for ACS 2022 P1 Test 1.

Run from this folder:  python _crop.py

It first prints each page's image/drawing bounding boxes so the rects below can
be tuned, then renders each figure region at zoom 3 to q<n>.png.

Workflow: run once, open the PNGs, adjust the (page_index, x0,y0,x1,y1) rects in
FIGS if anything is clipped, re-run. Watermark 'www.sgexam.com' sits top-right
(~x>430, y<60) and bottom-right (~y>790); the rects below avoid those.
Page size is approx 595 x 842 pt (A4 portrait).
"""
import fitz

doc = fitz.open("paper.pdf")

# ---- diagnostics: dump image + drawing bboxes so rects can be verified ----
for i in range(doc.page_count):
    p = doc[i]
    info = p.get_image_info()
    if info:
        print(f"page {i+1} rect={tuple(round(v,1) for v in p.rect)}")
        for im in info:
            print("   img bbox", [round(v, 1) for v in im["bbox"]])

# ---- figure crops: (question_n, page_index_0based, x0, y0, x1, y1) ----
# page indices: Q1->p1(0), Q3->p2(1), Q7&Q8->p4(3), Q9&Q11->p5(4),
# Q12&Q13->p6(5), Q14&Q15->p7(6), Q16->p8(7), Q17->p9(8)
FIGS = [
    (1, 0, 120, 470, 360, 640),   # bears box
    (3, 1, 110, 430, 560, 560),   # elephant row A..G + '1st'
    (7, 3, 130, 175, 560, 300),   # number-pattern arrow boxes
    (8, 3, 150, 420, 360, 600),   # number bond ? / 5 / 9
    (9, 4, 120, 300, 560, 430),   # star with 12 + answer box
    (11, 4, 120, 620, 560, 920),  # four bees
    (12, 5, 150, 150, 560, 270),  # four number cards 13 16 8 20
    (13, 5, 120, 470, 560, 820),  # pineapples split + number-bond + eqn boxes
    (14, 6, 120, 200, 560, 320),  # bag row H..C + left/right
    (15, 6, 120, 600, 560, 800),  # Set A / Set B pencils
    (16, 7, 130, 330, 620, 620),  # goldfish + tortoises
    (17, 8, 120, 300, 720, 560),  # roses 12 + 7
]

mat = fitz.Matrix(3, 3)
for n, pidx, x0, y0, x1, y1 in FIGS:
    page = doc[pidx]
    clip = fitz.Rect(x0, y0, x1, y1)
    pix = page.get_pixmap(matrix=mat, clip=clip)
    out = f"q{n}.png"
    pix.save(out)
    print("wrote", out, "from page", pidx + 1, "clip", (x0, y0, x1, y1))

print("done")
