"""
engage_watch.py — Ctrl+Click the nearest small aibat ONCE, then watch its HP for
~6s WITHOUT re-clicking. If HP drops, 'click once and hold' is the right model.
"""
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

MOB_BOX = (0.455, 0.045, 0.650, 0.070)


def mob_hp(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]
    red = (r > 120) & (r > b + 50) & (r > g + 50)
    if int(red.sum()) < 150:
        return None
    cols = np.where(red.any(axis=0))[0]
    return (cols.max() + 1) / box.shape[1]


def grab(page):
    return cv2.imdecode(np.frombuffer(page.screenshot(), np.uint8), cv2.IMREAD_COLOR)


def main():
    with sync_playwright() as p:
        browser, page = get_page(p)
        w, h = viewport(page)
        _, cands = detect(grab(page))
        small = [c for c in cands if c[2] <= 600]
        if not small:
            print("no small aibat in view"); return
        small.sort(key=lambda c: -c[1])   # closest = lowest on screen
        mx, my, a = small[0]
        print(f"two-click (select, gap, attack) at ({mx:.0f},{my:.0f}) area={int(a)}; watch HP:")
        page.mouse.click(mx, my)          # select
        time.sleep(0.28)
        page.mouse.click(mx, my)          # attack the selected mob
        for i in range(9):
            time.sleep(0.7)
            m = mob_hp(grab(page))
            print(f"  t={i*0.7+0.7:.1f}s  mobHP={'gone' if m is None else f'{m*100:.0f}%'}")


if __name__ == "__main__":
    main()
