#!/opt/homebrew/bin/python3.11
"""
Find the Inverted Jenny Stamp (Rose/Pink border)
"""

import cv2
import numpy as np
import os

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

# Keyframes to check
FRAMES = [
    "scan_6751.jpg",  # 112:31
    "scan_6755.jpg",  # 112:35
    "scan_6756.jpg",  # 112:36
    "scan_6759.jpg",  # 112:39
]

print("🔍 Searching for ROSE/CARMINE Stamps...")

for frame_name in FRAMES:
    img_path = os.path.join(BASE_DIR, frame_name)
    if not os.path.exists(img_path):
        continue

    img = cv2.imread(img_path)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # Define Rose/Carmine Pink Range
    # The stamp is Rose Pink.
    # Lower bound: Hue 165 (approx 330), Sat 100, Val 100
    # Upper bound: Hue 15, Sat 255, Val 255
    # Note: OpenCV Hue is 0-179. Pink is around 165-179 and 0-10.

    mask1 = cv2.inRange(hsv, np.array([155, 50, 50]), np.array([179, 255, 255]))
    mask2 = cv2.inRange(hsv, np.array([0, 50, 50]), np.array([10, 255, 255]))
    mask = mask1 + mask2

    contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    print(f"\n🎞️ Scanning {frame_name}...")
    found = False

    for cnt in contours:
        area = cv2.contourArea(cnt)
        x, y, w, h = cv2.boundingRect(cnt)

        # Filter: Stamp size (Small but visible, not noise, not face)
        # 200 < Area < 10000
        if 200 < area < 10000:
            # Filter: Aspect Ratio (Should be rectangular)
            aspect_ratio = float(w) / h
            # Stamps are roughly 0.6 to 1.5 ratio.
            if 0.4 < aspect_ratio < 2.5:
                print(
                    f"   ✅ Candidate Found: Area={int(area)}, Ratio={aspect_ratio:.2f}, Pos=({x},{y})"
                )

                # Draw
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)

                # Crop
                crop = img[y : y + h, x : x + w]
                crop_path = os.path.join(
                    BASE_DIR, f"crop_stamp_{frame_name}_{x}_{y}.jpg"
                )
                cv2.imwrite(crop_path, crop)
                found = True

    if found:
        res_path = os.path.join(BASE_DIR, f"result_pink_{frame_name}")
        cv2.imwrite(res_path, img)
    else:
        print("   ❌ No stamp candidates found.")
