"""
find_aibat.py — detect aibats (blue/purple blobs on tan ground) in the live
window and optionally Ctrl+Click the nearest one in ONE shot (no stale coords).

    python find_aibat.py          # detect only -> overlay.png, mask.png
    python find_aibat.py click    # detect + Ctrl+Click the nearest aibat

Tune HSV_LOWER/HSV_UPPER and ROI by inspecting mask.png / overlay.png.
"""
import sys
import time
import cv2
import numpy as np
from playwright.sync_api import sync_playwright
from session import get_page, viewport
from shots import shot_path

# Aibats are saturated blue/purple; tan ground is low-sat orange. Tune as needed.
HSV_LOWER = (110, 80, 40)
HSV_UPPER = (145, 255, 255)
# Region of interest as fractions (avoid UI: HP panel, minimap, chat, action bars).
ROI = (0.10, 0.12, 0.80, 0.62)   # x0, y0, x1, y1
MIN_AREA, MAX_AREA = 30, 4000


def detect(img):
    h, w = img.shape[:2]
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    mask = cv2.inRange(hsv, np.array(HSV_LOWER), np.array(HSV_UPPER))
    # zero everything outside the ROI
    roi = np.zeros_like(mask)
    x0, y0, x1, y1 = (int(ROI[0]*w), int(ROI[1]*h), int(ROI[2]*w), int(ROI[3]*h))
    roi[y0:y1, x0:x1] = 255
    mask = cv2.bitwise_and(mask, roi)
    mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((7, 7), np.uint8))
    cnts, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cands = []
    for c in cnts:
        a = cv2.contourArea(c)
        if MIN_AREA <= a <= MAX_AREA:
            M = cv2.moments(c)
            if M["m00"]:
                cx, cy = M["m10"]/M["m00"], M["m01"]/M["m00"]
                cands.append((cx, cy, a))
    return mask, cands


def main():
    click = "click" in sys.argv
    with sync_playwright() as p:
        browser, page = get_page(p)
        w, h = viewport(page)
        page.screenshot(path=shot_path("af.png"))
        img = cv2.imread(shot_path("af.png"))
        mask, cands = detect(img)

        cv2.imwrite(shot_path("mask.png"), mask)
        overlay = img.copy()
        cx0, cy0 = w/2, h*0.42
        cands.sort(key=lambda c: (c[0]-cx0)**2 + (c[1]-cy0)**2)  # nearest-to-center first
        for i, (cx, cy, a) in enumerate(cands):
            color = (0, 0, 255) if i == 0 else (0, 255, 0)
            cv2.circle(overlay, (int(cx), int(cy)), 14, color, 2)
            cv2.putText(overlay, f"{i}:{int(a)}", (int(cx)+10, int(cy)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 1)
        cv2.imwrite(shot_path("overlay.png"), overlay)

        print(f"viewport {w}x{h}; {len(cands)} candidate(s):")
        for i, (cx, cy, a) in enumerate(cands[:8]):
            print(f"  [{i}] frac=({cx/w:.3f},{cy/h:.3f}) area={int(a)}")

        if click and cands:
            cx, cy, _ = cands[0]
            print(f"-> Ctrl+Click nearest at ({cx:.0f},{cy:.0f})")
            page.keyboard.down("Control")
            page.mouse.click(cx, cy)
            page.keyboard.up("Control")
            time.sleep(2.5)
            page.screenshot(path=shot_path("atk_after.png"))
            print("saved screenshots/atk_after.png")


if __name__ == "__main__":
    main()
