#!/opt/homebrew/bin/python3.11
"""
Crop the detected stamp from the image.
"""

from PIL import Image
import os

UUID = "384b0ff44aaaa1f1"
BASE_DIR = f"output/{UUID}/florence2_results"
IMG_NAME = "raw_6846.jpg"
img_path = os.path.join(BASE_DIR, IMG_NAME)

# Coordinates from the successful run that detected 'stamp'
# Format: [x_min, y_min, x_max, y_max]
box = [1721.28, 23.22, 1813.44, 173.34]

print(f"📷 Loading image: {img_path}")
if not os.path.exists(img_path):
    print("❌ Image not found.")
    exit()

try:
    img = Image.open(img_path)
    print(f"📐 Image Size: {img.width}x{img.height}")

    # Convert float coordinates to int
    box_int = [int(x) for x in box]
    print(f"✂️ Cropping box: {box_int}")

    # Crop the image
    cropped = img.crop(box_int)

    # Save
    out_path = os.path.join(BASE_DIR, "stamp_crop_detected.jpg")
    cropped.save(out_path)
    print(f"✅ Successfully saved cropped stamp to {out_path}")

except Exception as e:
    print(f"❌ Error: {e}")
