#!/opt/homebrew/bin/python3.11
"""
Crop Top Candidates for Stamp
"""

import cv2
import os

UUID = "384b0ff44aaaa1f1"
BASE_DIR = f"output/{UUID}/florence2_results"

# Top candidates based on Pink Area (Inverted Jenny Plane)
CANDIDATES = [
    ("scan_6756.jpg", 383, 150, 289, 244, "High Pink Area"),
    ("scan_6790.jpg", 1084, 319, 126, 272, "Very High Pink Area"),
    ("scan_6813.jpg", 1713, 26, 147, 294, "Highest Pink Area"),
    ("scan_6832.jpg", 1664, 560, 256, 176, "High Pink Area"),
    ("scan_6756.jpg", 1236, 28, 92, 152, "Secondary Candidate"),
]

print("✂️ Cropping Top Stamp Candidates...")

for img_name, x, y, w, h, reason in CANDIDATES:
    img_path = os.path.join(BASE_DIR, img_name)
    if not os.path.exists(img_path):
        continue

    img = cv2.imread(img_path)
    h_img, w_img, _ = img.shape

    # Ensure coordinates are within image bounds
    x1 = max(0, x)
    y1 = max(0, y)
    x2 = min(w_img, x + w)
    y2 = min(h_img, y + h)

    crop = img[y1:y2, x1:x2]
    out_name = f"top_candidate_{img_name.replace('.jpg', '')}_{x}_{y}.jpg"
    out_path = os.path.join(BASE_DIR, out_name)

    cv2.imwrite(out_path, crop)
    print(f"   ✅ Saved {out_name} (Reason: {reason})")

    # Also save a marked version of the full image
    cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 5)
    cv2.putText(
        img,
        f"STAMP? ({reason})",
        (x1, y1 - 10),
        cv2.FONT_HERSHEY_SIMPLEX,
        1,
        (0, 255, 0),
        2,
    )
    marked_name = f"marked_{img_name}"
    cv2.imwrite(os.path.join(BASE_DIR, marked_name), img)

print("🏁 Done. Please check the 'top_candidate' files.")
