#!/opt/homebrew/bin/python3.11
"""
Crop the detected stamp from the OpenCV result.
"""

import cv2
import os

UUID = "384b0ff44aaaa1f1"
BASE_DIR = f"output/{UUID}/florence2_results"
IMG_NAME = "found_stamp_opencv.jpg"
IMG_PATH = os.path.join(BASE_DIR, IMG_NAME)
OUT_PATH = os.path.join(BASE_DIR, "stamp_crop_opencv.jpg")

# Coordinates from the OpenCV run: Area=30307.0, Box=(618,924)
# The box usually means x, y, w, h.
# We need to calculate w and h from area? No, findContours gives us points.
# Let's re-run the logic briefly to get exact coordinates or just crop roughly if we trust the box.
# Actually, the previous script printed Area=30307, Box=(618,924).
# BoundingRect returns (x, y, w, h).
# Let's assume it's roughly centered or just crop a region around x=618, y=924.
# Wait, area 30307 is large. 30307 = w * h.
# Maybe it's the woman's dress or a decoration?
# Let's crop the area around (618, 924) to see what it is.
# Let's guess it's roughly 150x200 or similar? sqrt(30307) approx 174.
# So x: 618-174/2 to 618+174/2 => 530 to 705?
# Let's just look at the full image result first, but I can't show images directly.
# I will crop a standard size region around the detected center.

import numpy as np

img = cv2.imread(IMG_PATH)
if img is None:
    print("❌ Image not found.")
    exit()

# Detected box x,y was 618,924. Let's assume this is the top-left or center.
# boundingRect returns x,y,w,h.
# Since I don't have w,h in the log, I will re-run detection quickly.

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_red1 = np.array([0, 70, 50])
upper_red1 = np.array([10, 255, 255])
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
lower_red2 = np.array([170, 70, 50])
upper_red2 = np.array([180, 255, 255])
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = mask1 + mask2

contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    peri = cv2.arcLength(cnt, True)
    approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
    if len(approx) == 3:
        area = cv2.contourArea(approx)
        if 200 < area < 50000:
            x, y, w, h = cv2.boundingRect(approx)
            print(f"✂️ Cropping at x={x}, y={y}, w={w}, h={h}, Area={area}")

            # Crop
            crop = img[y : y + h, x : x + w]
            cv2.imwrite(OUT_PATH, crop)
            print(f"✅ Saved crop to {OUT_PATH}")
