"""Crop ONE figure from a paper PDF to a PNG. Used by image-extraction agents.

Usage:
  python _cropone.py <pdf> <page1based> <x0> <y0> <x1> <y1> <out.png>

x0,y0,x1,y1 are FRACTIONS of the page (0..1), top-left origin. Renders at 3x.
Prints the output size so the agent can sanity-check before/after viewing it.
"""
import sys, os
import fitz
from PIL import Image

def main():
    pdf = sys.argv[1]; page = int(sys.argv[2])
    x0, y0, x1, y1 = (float(sys.argv[i]) for i in range(3, 7))
    out = sys.argv[7]
    doc = fitz.open(pdf)
    if page < 1 or page > doc.page_count:
        print("ERR bad page %d (doc has %d)" % (page, doc.page_count)); return
    pg = doc[page - 1]; R = pg.rect; W = R.width; H = R.height
    clip = fitz.Rect(x0 * W, y0 * H, x1 * W, y1 * H)
    if clip.is_empty or clip.width < 3 or clip.height < 3:
        print("ERR empty/tiny clip"); return
    pix = pg.get_pixmap(matrix=fitz.Matrix(3, 3), clip=clip, colorspace=fitz.csRGB)
    im = Image.frombytes("RGB", (pix.width, pix.height), pix.samples)
    os.makedirs(os.path.dirname(out), exist_ok=True)
    im.save(out)
    doc.close()
    print("OK %s  %dx%d" % (out, im.width, im.height))

if __name__ == "__main__":
    main()
