"""hp_diag.py — read hp_fraction from the live window and save an annotated crop of
the HP-bar region so we can see what the detector picks up. Run: python hp_diag.py"""
import urllib.request
import cv2
import numpy as np
from playwright.sync_api import sync_playwright
import grind_local as gl
from shots import shot_path


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


def main():
    with sync_playwright() as pw:
        page = pw.chromium.connect_over_cdp(f"http://127.0.0.1:{port()}").contexts[0].pages[0]
        img = cv2.imdecode(np.frombuffer(page.screenshot(), np.uint8), cv2.IMREAD_COLOR)
        h, w = img.shape[:2]
        frac = gl.hp_fraction(img)
        # the band hp_fraction reads
        y0, y1 = gl.HP_Y0, gl.HP_Y1
        x0, x1 = gl.HP_X0, gl.HP_X1
        fl, fr = gl.FILL_L, gl.FILL_R
        box = img[y0:y1, x0:x1].astype(int)
        r, g, b = box[:, :, 2], box[:, :, 1], box[:, :, 0]
        red = (r > 110) & (r > b + 40) & (r > g + 25)
        xs = np.where(red.any(axis=0))[0]
        rightmost = (xs.max() + x0) if len(xs) else None
        print(f"viewport {w}x{h}")
        print(f"hp_fraction = {frac:.3f}  ({int(frac*100)}%)")
        print(f"read band: y[{y0}:{y1}] x[{x0}:{x1}]  fill-span fl={fl} fr={fr}")
        print(f"red pixels found: {int(red.sum())}; rightmost red x = {rightmost}")

        # annotated wide crop around the bars (a bit above/below the read band)
        cy0, cy1 = max(0, y0-20), min(h, y1+60)
        cx0, cx1 = max(0, x0-20), min(w, x1+40)
        crop = img[cy0:cy1, cx0:cx1].copy()
        # mark the read band (yellow), fl/fr (green/blue), rightmost red (magenta)
        cv2.rectangle(crop, (x0-cx0, y0-cy0), (x1-cx0, y1-cy0), (0, 255, 255), 1)
        cv2.line(crop, (fl-cx0, 0), (fl-cx0, crop.shape[0]), (0, 255, 0), 1)
        cv2.line(crop, (fr-cx0, 0), (fr-cx0, crop.shape[0]), (255, 0, 0), 1)
        if rightmost is not None:
            cv2.line(crop, (rightmost-cx0, 0), (rightmost-cx0, crop.shape[0]), (255, 0, 255), 1)
        big = cv2.resize(crop, None, fx=4, fy=4, interpolation=cv2.INTER_NEAREST)
        cv2.imwrite(shot_path("hp_diag.png"), big)
        print("saved screenshots/hp_diag.png  (yellow=read band, green=fl, blue=fr, magenta=detected fill edge)")


if __name__ == "__main__":
    main()
