"""
hp_crop_test.py — grab a LIVE screenshot from the running game and dump the HP-bar crop
(with the detection box + fill lines drawn) so we can verify the crop is right for THIS
resolution. Saves images to ./hpCropTest. Run while the game window is open:  python hp_crop_test.py
"""
import os
import urllib.request
import cv2
import numpy as np
from playwright.sync_api import sync_playwright
import grind_local as gl

OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hpCropTest")


def find_port(a=9222, b=9251):
    for p in range(a, b):
        try:
            urllib.request.urlopen(f"http://127.0.0.1:{p}/json/version", timeout=0.3)
            return p
        except Exception:
            pass
    return None


def main():
    os.makedirs(OUT, exist_ok=True)
    port = find_port()
    if not port:
        print("No CDP debug port found — is the game (flyffbot / host) running?")
        return
    with sync_playwright() as pw:
        browser = pw.chromium.connect_over_cdp(f"http://127.0.0.1:{port}")
        page = browser.contexts[0].pages[0]
        img = cv2.imdecode(np.frombuffer(page.screenshot(), np.uint8), cv2.IMREAD_COLOR)
    w, h, redpx = gl.dump_hp_crop(img, OUT)
    print(f"resolution {w}x{h}, red_px={redpx} — saved crops to {OUT}")


if __name__ == "__main__":
    main()
