"""
Crops figures from paper.pdf into q<n>.png (and q<n>_optK.png for image-option MCQs).
Rects are estimates in PDF points; view each PNG and adjust if clipped/loose.
Run:  python crop.py
"""
import fitz

ZOOM = 3
M = fitz.Matrix(ZOOM, ZOOM)
d = fitz.open("paper.pdf")
PW, PH = d[0].rect.width, d[0].rect.height
print(f"page size: {PW} x {PH}")

# (filename, page_index_0based, x0, y0, x1, y1)  rough estimates -> verify visually
crops = [
    # Q1 clock face (page 1)
    ("q1.png", 0, 270, 390, 360, 480),

    # Q2 four option clocks (page 2)
    ("q2_opt0.png", 1, 150, 290, 240, 380),
    ("q2_opt1.png", 1, 150, 390, 240, 480),
    ("q2_opt2.png", 1, 150, 490, 240, 580),
    ("q2_opt3.png", 1, 150, 590, 240, 680),

    # Q3 row of coins (page 3)
    ("q3.png", 2, 165, 175, 460, 255),

    # Q4 pencil + price tag (page 3)
    ("q4.png", 2, 140, 425, 380, 510),

    # Q5 four coin-set options (page 4)
    ("q5_opt0.png", 3, 150, 170, 470, 240),
    ("q5_opt1.png", 3, 150, 255, 470, 325),
    ("q5_opt2.png", 3, 150, 345, 420, 415),
    ("q5_opt3.png", 3, 150, 435, 300, 505),

    # Q6 four note/coin-set options (page 5)
    ("q6_opt0.png", 4, 150, 180, 440, 270),
    ("q6_opt1.png", 4, 150, 305, 470, 395),
    ("q6_opt2.png", 4, 150, 430, 480, 510),
    ("q6_opt3.png", 4, 150, 545, 470, 660),

    # Q7 row of coins to circle (page 6)
    ("q7.png", 5, 120, 230, 430, 305),
]

for fn, pi, x0, y0, x1, y1 in crops:
    page = d[pi]
    clip = fitz.Rect(x0, y0, x1, y1)
    pix = page.get_pixmap(matrix=M, clip=clip)
    pix.save(fn)
    print(f"wrote {fn}  ({pix.width}x{pix.height})")

print("done")
