"""Probe full Hillsborough PA flow — landing → search → detail."""
from pathlib import Path
import time


def probe():
    from playwright.sync_api import sync_playwright

    out_dir = Path(__file__).parent.parent / "_probe_out" / "hcpa"
    out_dir.mkdir(parents=True, exist_ok=True)
    parcel = "1932071V5000000002960U"

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_context(user_agent="Mozilla/5.0 Chrome/131").new_page()

        # Capture all GET XHR calls to find the property data API
        captured = []
        page.on("request", lambda req: captured.append({"m": req.method, "url": req.url})
                  if req.method in ("GET", "POST") else None)

        # Land on the GIS PropertySearch SPA
        page.goto("https://gis.hcpafl.org/propertysearch/", wait_until="domcontentloaded")
        time.sleep(7)
        print(f"Landing URL: {page.url}")
        print(f"Title: {page.title()}")

        # Look for inputs visible
        inputs = page.locator("input:visible").all()
        print(f"\nVisible inputs ({len(inputs)}):")
        for inp in inputs[:10]:
            try:
                id_ = inp.get_attribute("id") or ""
                name = inp.get_attribute("name") or ""
                ph = inp.get_attribute("placeholder") or ""
                aria = inp.get_attribute("aria-label") or ""
                print(f"  id={id_!r} name={name!r} placeholder={ph!r} aria={aria!r}")
            except Exception:
                pass

        # Try to fill the folio input — find any input that mentions 'folio'
        folio_input = page.locator(
            "input[placeholder*='folio' i], input[aria-label*='folio' i], "
            "input[placeholder*='parcel' i], input[name*='folio' i]"
        ).first
        if folio_input.count() > 0:
            print("\nFilling folio input...")
            folio_input.fill(parcel)
            time.sleep(1)
            # Press Enter or click Search
            page.keyboard.press("Enter")
            time.sleep(8)
            print(f"After search URL: {page.url}")
            body = page.inner_text("body")[:1000]
            print(f"Body: {body.encode('ascii','replace').decode('ascii')[:800]}")

        # Filter captured to property-data calls
        print(f"\nRelevant network calls ({len(captured)} total):")
        for c in captured[-20:]:
            if any(kw in c["url"] for kw in ("Property", "Folio", "Parcel", "GetProp", "json")):
                print(f"  {c['m']} {c['url'][:150]}")

        browser.close()


if __name__ == "__main__":
    probe()
