"""
click_diag.py [dy] — mark detected centroid (red) and click point at +dy (green)
on a live frame; save full overlay + zoom around nearest aibat to measure offset.
"""
import sys
import cv2
import numpy as np
from playwright.sync_api import sync_playwright
from session import get_page, viewport
from find_aibat import detect
from shots import shot_path

dy = int(sys.argv[1]) if len(sys.argv) > 1 else 24


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]
        cx0, cy0 = w/2, h*0.45
        small.sort(key=lambda c: (c[0]-cx0)**2 + (c[1]-cy0)**2)

        ov = img.copy()
        for mx, my, a in small:
            cv2.circle(ov, (int(mx), int(my)), 3, (0, 0, 255), -1)
            cv2.drawMarker(ov, (int(mx), int(my+dy)), (0, 255, 0), cv2.MARKER_CROSS, 18, 2)
        cv2.imwrite(shot_path("clickdiag.png"), ov)

        if small:
            mx, my, a = small[0]
            x0, y0 = max(0, int(mx-70)), max(0, int(my-50))
            crop = ov[y0:int(my+100), x0:int(mx+70)]
            cv2.imwrite(shot_path("clickzoom.png"), cv2.resize(crop, None, fx=4, fy=4,
                        interpolation=cv2.INTER_NEAREST))
            print(f"nearest centroid=({mx:.0f},{my:.0f}) area={int(a)} "
                  f"click=({mx:.0f},{my+dy:.0f}) dy={dy}")
        print(f"{len(small)} small candidate(s)")


if __name__ == "__main__":
    main()
