#!/opt/homebrew/bin/python3.11
"""
Find REALISTIC red stamps using OpenCV
Filter: Triangle/Rect Shape + Realistic Area Size (Visible to Eye)
"""

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 (Dialogue: "Give me the stamp")
    "scan_6759.jpg",  # 112:39
]

print("🔍 Analyzing Keyframes for REALISTIC 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)
    h, w, _ = img.shape

    # Convert to HSV
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    # Red Mask
    mask1 = cv2.inRange(hsv, np.array([0, 70, 50]), np.array([10, 255, 255]))
    mask2 = cv2.inRange(hsv, np.array([170, 70, 50]), np.array([180, 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)

        # FILTER 1: Area Size (Must be visible but smaller than a face)
        # Face ~ 20,000px. Stamp ~ 500px to 15,000px.
        if area < 500 or area > 15000:
            continue

        # FILTER 2: Shape (Triangle or Rectangle)
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)

        # Check for 3 (triangle) or 4 (rectangle) vertices
        if len(approx) in [3, 4]:
            x, y, w_box, h_box = cv2.boundingRect(approx)
            print(
                f"   ✅ Found Stamp Candidate: Area={area}, Size={w_box}x{h_box}, Pos=({x},{y})"
            )

            # Draw
            cv2.rectangle(img, (x, y), (x + w_box, y + h_box), (0, 255, 0), 3)
            cv2.putText(
                img,
                f"STAMP ({area})",
                (x, y - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.8,
                (0, 255, 0),
                2,
            )

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

    if found:
        res_path = os.path.join(BASE_DIR, f"result_realistic_{frame_name}")
        cv2.imwrite(res_path, img)
        print(f"   🎨 Result saved to: result_realistic_{frame_name}")
    else:
        print("   ❌ No realistic stamps found (filtered out noise/background).")
