#!/opt/homebrew/bin/python3.11
"""
Detect stamp-like rectangular regions with Blue+Red colors in full frames
"""

import cv2
import numpy as np
import os
import glob

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

print("🔍 Searching for stamp-like rectangles in full frames...")

scan_frames = sorted(glob.glob(os.path.join(BASE_DIR, "scan_*.jpg")))
print(f"Found {len(scan_frames)} scan frames.")

for frame_path in scan_frames:
    img = cv2.imread(frame_path)
    if img is None:
        continue

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

    # Detect Blue regions
    blue_mask = cv2.inRange(hsv, np.array([90, 30, 30]), np.array([130, 255, 255]))

    # Detect Red regions
    red_mask1 = cv2.inRange(hsv, np.array([0, 30, 30]), np.array([10, 255, 255]))
    red_mask2 = cv2.inRange(hsv, np.array([170, 30, 30]), np.array([179, 255, 255]))
    red_mask = red_mask1 + red_mask2

    # Combine: areas that have BOTH blue and red nearby
    combined = cv2.bitwise_and(blue_mask, red_mask)

    # Actually, let's find contours in blue areas and check if they contain red inside
    contours, _ = cv2.findContours(
        blue_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
    )

    stamp_candidates = []

    for contour in contours:
        # Filter by area (stamps are medium-sized)
        area = cv2.contourArea(contour)
        if area < 500 or area > 50000:
            continue

        # Get bounding rectangle
        x, y, w, h = cv2.boundingRect(contour)
        aspect_ratio = w / h if h > 0 else 0

        # Stamps are roughly rectangular (aspect ratio 0.5-2.0)
        if aspect_ratio < 0.4 or aspect_ratio > 2.5:
            continue

        # Check if this blue region contains red pixels inside
        roi_red = red_mask[y : y + h, x : x + w]
        red_pixels = cv2.countNonZero(roi_red)
        red_ratio = red_pixels / (w * h) if w * h > 0 else 0

        # If there's significant red inside the blue region, it's a stamp candidate
        if red_ratio > 0.05:
            stamp_candidates.append((x, y, w, h, area, red_ratio))
            # Draw rectangle on the image
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)
            cv2.putText(
                img,
                f"Red:{red_ratio:.1%}",
                (x, y - 10),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.6,
                (0, 255, 0),
                2,
            )

    if stamp_candidates:
        print(
            f"\n📍 {os.path.basename(frame_path)}: Found {len(stamp_candidates)} candidates"
        )
        for x, y, w, h, area, red_ratio in stamp_candidates:
            print(f"   ({x},{y}) size={w}x{h} area={area} red={red_ratio:.1%}")

        # Save annotated image
        out_name = "STAMP_DETECTED_" + os.path.basename(frame_path)
        cv2.imwrite(os.path.join(BASE_DIR, out_name), img)

        # Also extract and save each candidate region
        for i, (x, y, w, h, area, red_ratio) in enumerate(stamp_candidates):
            crop = img[y : y + h, x : x + w]
            crop_name = f"STAMP_CROP_{os.path.basename(frame_path)[:-4]}_{i}.jpg"
            cv2.imwrite(os.path.join(BASE_DIR, crop_name), crop)

print("\n🏁 Done. Check files named 'STAMP_DETECTED_*' and 'STAMP_CROP_*'")
