"""
clicktest.py [dy] — Ctrl+Click the nearest small aibat at centroid+dy and report
whether it ENGAGED (target frame / mob HP bar appeared). Finds the right offset.
"""
import sys
import time
import cv2
import numpy as np
from playwright.sync_api import sync_playwright
from session import get_page, viewport
from find_aibat import detect

dy = int(sys.argv[1]) if len(sys.argv) > 1 else 0
MOB_BOX = (0.455, 0.045, 0.650, 0.070)


def mob_targeted(img):
    h, w = img.shape[:2]
    x0, y0, x1, y1 = (int(MOB_BOX[0]*w), int(MOB_BOX[1]*h),
                      int(MOB_BOX[2]*w), int(MOB_BOX[3]*h))
    box = img[y0:y1, x0:x1].astype(int)
    r, g, b = box[:, :, 2], box[:, :, 1], box[:, :, 0]
    return int(((r > 120) & (r > b + 50) & (r > g + 50)).sum())


def main():
    with sync_playwright() as p:
        browser, page = get_page(p)
        w, h = viewport(page)
        png = page.screenshot()
        img = cv2.imdecode(np.frombuffer(png, np.uint8), cv2.IMREAD_COLOR)
        _, cands = detect(img)
        small = [c for c in cands if c[2] <= 600]
        if not small:
            print("no small aibat in view"); return
        cx0, cy0 = w/2, h*0.45
        small.sort(key=lambda c: (c[0]-cx0)**2 + (c[1]-cy0)**2)
        mx, my, a = small[0]
        print(f"clicking centroid=({mx:.0f},{my:.0f}) +dy={dy} -> ({mx:.0f},{my+dy:.0f})")
        page.keyboard.down("Control"); page.mouse.click(mx, my+dy); page.keyboard.up("Control")
        time.sleep(1.2)
        after = cv2.imdecode(np.frombuffer(page.screenshot(), np.uint8), cv2.IMREAD_COLOR)
        red = mob_targeted(after)
        print(f"target-frame red px after click: {red}  -> {'ENGAGED' if red>150 else 'missed'}")


if __name__ == "__main__":
    main()
