import sys
import os
import time
from pathlib import Path
from PIL import Image

sys.path.insert(0, r"c:\Projects\AutoPOE2")

from src.common.win32_window import find_poe2_window, ensure_window_focus, get_client_rect
from src.common.win32_input import hover
from src.assistant_tool.screen_capturer import ScreenCapturer
import winocr

hwnd = find_poe2_window()
ensure_window_focus(hwnd)
rect = get_client_rect(hwnd)
cap = ScreenCapturer(output_dir="captures")

print(f"Scanning window {rect}...", flush=True)

found = []
for y in range(250, 750, 60):
    for x in range(300, 900, 60):
        hover(rect[0] + x, rect[1] + y, delay_after=0.10)
        p = cap.capture_screenshot("NODE_PROBE", capture_ram=False)
        img = Image.open(p)
        x1, y1 = max(0, x - 250), max(0, y - 200)
        x2, y2 = min(rect[2], x + 250), min(rect[3], y + 200)
        crop = img.crop((x1, y1, x2, y2))
        res = winocr.recognize_pil_sync(crop)
        blob = " ".join(l["text"] for l in res.get("lines", [])).upper()
        keywords = ["BIOME", "REQUIRES", "SOULS", "WELL", "TIER", "MONSTER", "DESERT", "GRASS", "VAULT", "RUINS", "FIELDS", "MINESHAFT"]
        if any(k in blob for k in keywords):
            lines = [l["text"] for l in res["lines"] if any(k in l["text"].upper() for k in keywords)]
            print(f"FOUND NODE AT ({x}, {y}): {lines}", flush=True)
            found.append((x, y, lines))

print(f"DONE. Total nodes: {len(found)}", flush=True)
