"""
confirm_attack.py — unambiguous test that OUR Ctrl+Click selects+attacks a mob.
  1) deselect any current target (click empty ground)
  2) screenshot 'mid' -> must show NO target frame
  3) detect nearest SMALL aibat (area<=MAX_SMALL) and Ctrl+Click it
  4) screenshot 'post' -> should show a target frame IF our click worked
Saves mid_tf.png / post_tf.png (zoomed target-frame region) for comparison.
"""
import time
import cv2
from playwright.sync_api import sync_playwright
from session import get_page, viewport
from find_aibat import detect
from shots import shot_path

MAX_SMALL = 600   # px area; bigger blue blobs are giant/too-strong aibats


def crop_tf(src, dst):
    im = cv2.imread(src)
    H, W = im.shape[:2]
    cr = im[0:int(0.12*H), int(0.35*W):int(0.68*W)]
    cv2.imwrite(dst, cv2.resize(cr, None, fx=3, fy=3, interpolation=cv2.INTER_NEAREST))


def main():
    with sync_playwright() as p:
        browser, page = get_page(p)
        w, h = viewport(page)

        # 1) deselect current target by clicking empty ground high in the field
        page.mouse.click(w*0.5, h*0.13)
        time.sleep(1.0)
        page.screenshot(path=shot_path("mid.png"))

        # 2) detect small aibats from a fresh frame
        page.screenshot(path=shot_path("cur.png"))
        _, cands = detect(cv2.imread(shot_path("cur.png")))
        small = [c for c in cands if c[2] <= MAX_SMALL]
        cx0, cy0 = w/2, h*0.42
        small.sort(key=lambda c: (c[0]-cx0)**2 + (c[1]-cy0)**2)
        print(f"{len(cands)} total blue blobs, {len(small)} small (area<={MAX_SMALL})")

        if not small:
            print("no SMALL aibat in view — reposition so a small one is visible.")
        else:
            cx, cy, a = small[0]
            print(f"-> Ctrl+Click small aibat frac=({cx/w:.3f},{cy/h:.3f}) area={a}")
            page.keyboard.down("Control")
            page.mouse.click(cx, cy)
            page.keyboard.up("Control")
            time.sleep(2.5)

        page.screenshot(path=shot_path("post.png"))
        crop_tf(shot_path("mid.png"), shot_path("mid_tf.png"))
        crop_tf(shot_path("post.png"), shot_path("post_tf.png"))
        print("saved screenshots/mid_tf.png (before, expect NO frame) and post_tf.png (after, expect frame)")


if __name__ == "__main__":
    main()
