import cv2, os, uuid
from app.config import settings

def crop_article(page_image, bbox, out_dir, pad=15):
    x, y, w, h = [int(v) for v in bbox]
    img_h, img_w = page_image.shape[:2]
    
    x1 = max(0, x - pad)
    y1 = max(0, y - pad)
    x2 = min(img_w, x + w + pad)
    y2 = min(img_h, y + h + pad)
    
    crop = page_image[y1:y2, x1:x2]
    os.makedirs(out_dir, exist_ok=True)
    path = os.path.join(out_dir, f"article_{uuid.uuid4().hex[:8]}.png")
    cv2.imwrite(path, cv2.cvtColor(crop, cv2.COLOR_RGB2BGR))
    return path

def crop_figures(page_image, article, out_dir):
    paths = []
    for b in article["blocks"]:
        if b["type"] == "Figure":
            paths.append(crop_article(page_image, _xywh(b["bbox"]), out_dir, pad=5))
    return paths

def _xywh(box):
    return [box[0], box[1], box[2]-box[0], box[3]-box[1]]
