import sys
sys.path.insert(0, ".")
from PIL import Image
import src.common.vision_ocr as vo

p = 'captures/pipeline_run/20260920_082700_994_STAGE2_MAP_DEVICE_HOVERED.png'
img = Image.open(p)
w, h = img.size
print(f"Image size: {w}x{h}")

# Step 1: Multi-region OCR
regions = [
    (int(w * 0.10), int(h * 0.05), int(w * 0.48), int(h * 0.50)),
    (0, 0, int(w * 0.60), int(h * 0.70)),
    (int(w * 0.35), 0, int(w * 0.90), int(h * 0.70)),
    (0, 0, w, int(h * 0.85)),
]
for idx, (rx1, ry1, rx2, ry2) in enumerate(regions):
    crop_img = img.crop((rx1, ry1, rx2, ry2))
    res = vo.safe_recognize_pil_sync(crop_img)
    for line in res.get("lines", []):
        text = line.get("text", "").upper()
        clean = text.replace(" ", "").replace("'", "")
        if (
            "DEVICE" in clean
            or "MAPDEV" in clean
            or ("MAPD" in clean and any(k in clean for k in ["EVI", "FC", "TNC", "RR"]))
            or any(d in clean for d in ["UEVICE", "WEVICE", "EVICE"])
            or ("MAP" in text and any(d in clean for d in ["DEV", "DEVI", "EVI"]))
        ):
            print(f"Region {idx} MATCHED: text='{text}', clean='{clean}'")
            words = line.get("words", [])
            print("Words:", words)
            valid_words = [
                w_info for w_info in words
                if not ((w_info["bounding_rect"]["x"] + rx1) > 0.90 * w and (w_info["bounding_rect"]["y"] + ry1) < 0.18 * h)
                and 0.02 * w <= (w_info["bounding_rect"]["x"] + rx1) <= 0.98 * w
            ]
            matched_words = [
                w_info for w_info in valid_words
                if any(k in w_info.get("text", "").upper() for k in ["MAP", "DEV", "DEVICE", "UEVICE", "WEVICE", "EVICE"])
                or w_info.get("text", "").upper().replace(" ", "").replace("'", "") in ["D", "EVI", "FC", "TNC"]
            ]
            target_words = matched_words if matched_words else valid_words
            min_x = min(w_info["bounding_rect"]["x"] for w_info in target_words) + rx1
            max_x = max(w_info["bounding_rect"]["x"] + w_info["bounding_rect"]["width"] for w_info in target_words) + rx1
            min_y = min(w_info["bounding_rect"]["y"] for w_info in target_words) + ry1
            max_y = max(w_info["bounding_rect"]["y"] + w_info["bounding_rect"]["height"] for w_info in target_words) + ry1
            sy = h / 1440.0
            cx = int((min_x + max_x) / 2)
            cy = int((min_y + max_y) / 2) + int(42 * sy)
            print(f"Calculated cx={cx}, cy={cy} (min_x={min_x}, max_x={max_x}, min_y={min_y}, max_y={max_y})")
