#!/opt/homebrew/bin/python3.11
"""
Crop stamp from magnifying glass scene at highest quality
"""

import cv2
import os

BASE_DIR = "output/384b0ff44aaaa1f1/stamp_closeup"
OUTPUT_DIR = "output/384b0ff44aaaa1f1/stamp_closeup/cropped"
os.makedirs(OUTPUT_DIR, exist_ok=True)

# Bounding boxes from OWL-ViT detection
# Format: [x1, y1, x2, y2]
DETECTIONS = {
    "5733": [519, 147, 1383, 931],  # Best frame
    "5734": [516, 147, 1384, 936],
    "5735": [528, 151, 1381, 936],
}

# Also extract a wider area to see context
WIDER_MARGIN = 100

for sec, bbox in DETECTIONS.items():
    frame_path = os.path.join(BASE_DIR, f"frame_{sec}s.jpg")
    img = cv2.imread(frame_path)
    if img is None:
        continue

    x1, y1, x2, y2 = bbox

    # 1. Crop exact detection area
    crop = img[y1:y2, x1:x2]
    if crop.size > 0:
        cv2.imwrite(os.path.join(OUTPUT_DIR, f"stamp_{sec}s_crop.jpg"), crop)
        print(f"  📍 {sec}s: Saved crop ({crop.shape[1]}x{crop.shape[0]})")

    # 2. Crop wider area with margin
    wx1 = max(0, x1 - WIDER_MARGIN)
    wy1 = max(0, y1 - WIDER_MARGIN)
    wx2 = min(img.shape[1], x2 + WIDER_MARGIN)
    wy2 = min(img.shape[0], y2 + WIDER_MARGIN)
    wide_crop = img[wy1:wy2, wx1:wx2]
    if wide_crop.size > 0:
        cv2.imwrite(os.path.join(OUTPUT_DIR, f"stamp_{sec}s_wide.jpg"), wide_crop)
        print(
            f"  📍 {sec}s: Saved wide crop ({wide_crop.shape[1]}x{wide_crop.shape[0]})"
        )

    # 3. Annotate full frame with green box
    annotated = img.copy()
    cv2.rectangle(annotated, (x1, y1), (x2, y2), (0, 255, 0), 4)
    cv2.putText(
        annotated,
        "STAMP AREA",
        (x1, y1 - 15),
        cv2.FONT_HERSHEY_SIMPLEX,
        1.0,
        (0, 255, 0),
        3,
    )
    cv2.imwrite(os.path.join(OUTPUT_DIR, f"annotated_{sec}s.jpg"), annotated)

    # 4. Draw on the original HQ frame too
    hq_path = os.path.join(BASE_DIR, f"frame_{sec}s.jpg")
    hq_img = cv2.imread(hq_path)
    if hq_img is not None:
        cv2.rectangle(hq_img, (x1, y1), (x2, y2), (0, 255, 0), 4)
        cv2.putText(
            hq_img,
            "STAMP",
            (x1, y1 - 15),
            cv2.FONT_HERSHEY_SIMPLEX,
            1.0,
            (0, 255, 0),
            3,
        )
        cv2.imwrite(os.path.join(OUTPUT_DIR, f"full_annotated_{sec}s.jpg"), hq_img)

print(f"\n🏁 Done. Check {OUTPUT_DIR}")
