"""Probe possible HUD deep-link URL patterns to find which one renders a single property."""
from __future__ import annotations
import io, sys, time
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")

from playwright.sync_api import sync_playwright

REAL_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
           "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")

# Real case # from earlier exploration
CASE_NUM = "093-676572"  # 4641 Samoset Dr, Sarasota

URLS_TO_PROBE = [
    f"https://www.hudhomestore.gov/searchresult?caseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/searchresult?CaseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/searchresult?searchText={CASE_NUM}",
    f"https://www.hudhomestore.gov/searchresult?cityStateZip={CASE_NUM}",
    f"https://www.hudhomestore.gov/Listing/PropertyDetails?caseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/Property/Details?caseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/PropertyDetails?caseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/Listing?caseNumber={CASE_NUM}",
    f"https://www.hudhomestore.gov/property/{CASE_NUM}",
    f"https://www.hudhomestore.gov/listing/{CASE_NUM}",
    f"https://www.hudhomestore.gov/casenumber/{CASE_NUM}",
]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_context(
        user_agent=REAL_UA, viewport={"width": 1400, "height": 900},
    ).new_page()
    page.set_default_timeout(15_000)

    # Set session via landing
    page.goto("https://www.hudhomestore.gov/", wait_until="networkidle")
    time.sleep(1.5)

    for url in URLS_TO_PROBE:
        print(f"\n=== {url} ===")
        try:
            r = page.goto(url, wait_until="networkidle", timeout=15_000)
            time.sleep(2)
            print(f"  status: {r.status}, final URL: {page.url}")
            body_text = page.locator("body").inner_text()
            # Heuristic: does the body show property-specific info?
            has_addr = "4641 Samoset" in body_text or "samoset" in body_text.lower()
            has_case = CASE_NUM in body_text
            has_price = "$446" in body_text
            has_specific_result_count = "1 Properties Listed" in body_text or "1 Property Listed" in body_text
            print(f"  has_address={has_addr}, has_case#={has_case}, has_price={has_price}, single_result={has_specific_result_count}")
            # If we found the address, this is likely the right URL
            if has_addr:
                print(f"  ✅ THIS URL RENDERS THE SPECIFIC PROPERTY")
        except Exception as e:
            print(f"  ERROR: {e}")

    # Also try the citystate flow + then drill into a single case
    # via the case number search input
    print()
    print("=== Step 7: Try entering case # in cityStateZip search ===")
    page.goto("https://www.hudhomestore.gov/", wait_until="networkidle")
    time.sleep(1.5)

    page.evaluate(f"""() => {{
        const inp = document.getElementById('cityStateZip');
        inp.value = '{CASE_NUM}';
        const event = new Event('input', {{ bubbles: true }});
        inp.dispatchEvent(event);
        if (typeof ysi !== 'undefined' && ysi.corpsearchfilter) {{
            ysi.corpsearchfilter.changeInput('{CASE_NUM}', 'home');
        }}
    }}""")
    time.sleep(3)

    # Inspect autocomplete + URL after
    print(f"  URL after typing case#: {page.url}")
    autocomplete_items = page.locator("#cityStateZipautocomplete-list li, [role='option']").all()
    print(f"  autocomplete suggestions: {len(autocomplete_items)}")
    for i, item in enumerate(autocomplete_items[:5]):
        text = (item.text_content() or "").strip()[:100]
        print(f"    [{i}] {text!r}")
    if autocomplete_items:
        try:
            autocomplete_items[0].click(force=True)
            time.sleep(3)
            print(f"  URL after selecting first: {page.url}")
        except Exception as e:
            print(f"  click failed: {e}")

    browser.close()
