"""Probar variantes del address 3245 Pearl St en Duval."""
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

USER_AGENT = "AR-House/1.0 (real estate investment analysis)"

variants = [
    {"num": "3245", "prefix": "N", "name": "PEARL", "suffix": "ST"},
    {"num": "3245", "prefix": "",  "name": "PEARL", "suffix": "ST"},
    {"num": "3245", "prefix": "",  "name": "PEARL", "suffix": ""},
    {"num": "3245", "prefix": "N", "name": "PEARL", "suffix": ""},
    # Probar otra direccion conocida (Jacksonville fl typical address)
    {"num": "1234", "prefix": "",  "name": "MAIN",  "suffix": "ST"},
]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    context = browser.new_context(user_agent=USER_AGENT)

    for v in variants:
        page = context.new_page()
        page.set_default_timeout(20_000)
        page.goto("https://paopropertysearch.coj.net/Basic/Search.aspx",
                  wait_until="networkidle", timeout=20_000)
        page.locator("#ctl00_cphBody_tbStreetNumber").fill(v["num"])
        if v["prefix"]:
            page.locator("#ctl00_cphBody_ddStreetPrefix").select_option(value=v["prefix"])
        page.locator("#ctl00_cphBody_tbStreetName").fill(v["name"])
        if v["suffix"]:
            try:
                page.locator("#ctl00_cphBody_ddStreetSuffix").select_option(value=v["suffix"])
            except Exception:
                pass

        page.evaluate("""() => {
            const form = document.forms[0] || document.querySelector('form');
            form.action = 'Results.aspx';
            let hidden = document.createElement('input');
            hidden.type = 'hidden';
            hidden.name = 'ctl00$cphBody$bSearch';
            hidden.value = 'Search';
            form.appendChild(hidden);
            form.submit();
        }""")
        try:
            page.wait_for_url("**Results.aspx**", timeout=10_000)
            page.wait_for_load_state("networkidle", timeout=8_000)
        except Exception as e:
            print(f"  variant {v}: submit fallo ({e})")
            page.close()
            continue

        # Check results
        body_text = page.locator("body").inner_text()
        if "No Results Found" in body_text:
            print(f"  variant {v}: NO RESULTS")
        elif "No information available" in body_text:
            print(f"  variant {v}: NO INFO AVAILABLE")
        else:
            # Print first table info
            tables = page.locator("table").all()
            print(f"  variant {v}: {len(tables)} tables")
            for t in tables[:1]:
                rows = t.locator("tr").all()
                for j, r in enumerate(rows[:3]):
                    cells = r.locator("td, th").all()
                    texts = [(c.text_content() or "").strip()[:40] for c in cells]
                    print(f"    Row {j}: {texts}")

        page.close()
        time.sleep(2)  # rate limit

    browser.close()
