"""Probe Civitek Case Search tab structure."""
from pathlib import Path


def probe():
    from playwright.sync_api import sync_playwright

    out_dir = Path(__file__).parent.parent / "_probe_out" / "civitek"

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_context().new_page()

        # Walk to search
        page.goto("https://www.civitekflorida.com/ocrs/county/27/")
        page.wait_for_timeout(1500)
        page.locator("button:has-text('Public')").first.click()
        page.wait_for_timeout(2500)
        page.locator("button:has-text('I Agree')").first.click()
        page.wait_for_timeout(2500)

        # Click "Case Search" tab (data-index=1)
        print("[1] Clicking 'Case Search' tab...")
        case_tab = page.locator("li[role='tab']:has-text('Case Search')").first
        case_tab.click()
        page.wait_for_timeout(2500)
        (out_dir / "05_case_search_tab.html").write_text(page.content(), encoding="utf-8")

        # Find new fields exposed under Case Search tab
        print("\n[2] Inputs visible after switching tab:")
        for inp in page.locator("input:visible, select:visible").all()[:30]:
            try:
                tag = inp.evaluate("el => el.tagName.toLowerCase()")
                id_ = inp.get_attribute("id") or ""
                name = inp.get_attribute("name") or ""
                type_ = inp.get_attribute("type") or ""
                placeholder = inp.get_attribute("placeholder") or ""
                if type_ == "hidden":
                    continue
                # Get label
                label_for = ""
                if id_:
                    lbl = page.locator(f"label[for='{id_}']").first
                    if lbl.count() > 0:
                        label_for = lbl.inner_text()[:50]
                print(f"    <{tag}> id={id_!r} type={type_!r} label={label_for!r}")
            except Exception:
                pass

        # Test: search for a known case_number from our realauction inventory
        # Most realauction cases are like "2024-CA-001234" or "23-2024-CA-001234"
        # Try a generic test case number first to see the UI behavior
        print("\n[3] Looking for case_number input field name...")
        case_inputs = page.locator("input[id*='case' i], input[id*='Case'], input[name*='case' i]").all()
        for inp in case_inputs[:5]:
            try:
                id_ = inp.get_attribute("id") or ""
                name = inp.get_attribute("name") or ""
                print(f"    case-like input: id={id_!r} name={name!r}")
            except Exception:
                pass

        # Submit empty to see validation errors
        print("\n[4] Submitting empty Case Search to see required fields...")
        search_btn = page.locator("button:has(.ui-button-text:text-is('Search'))").first
        if search_btn.count() == 0:
            search_btn = page.locator("button:has-text('Search')").first
        try:
            search_btn.click()
            page.wait_for_timeout(2500)
        except Exception as e:
            print(f"    click error: {e}")

        # Capture error messages
        print("\n[5] Validation messages after empty submit:")
        for sel in [".ui-messages-error", ".ui-message-error", ".ui-message"]:
            for m in page.locator(sel).all()[:5]:
                try:
                    t = (m.inner_text() or "").strip()[:200]
                    if t:
                        print(f"    [{sel}] {t}")
                except Exception:
                    pass

        (out_dir / "06_case_search_empty_submit.html").write_text(page.content(), encoding="utf-8")
        page.screenshot(path=str(out_dir / "06_case_search.png"), full_page=True)
        print(f"\n[OK] saved to {out_dir}/")
        browser.close()


if __name__ == "__main__":
    probe()
