import sys
from playwright.sync_api import sync_playwright
from _pw import get_ffg_page

section = sys.argv[1] if len(sys.argv) > 1 else None

def label_for(page, el):
    # try associated <label for=id>, else preceding text
    eid = el.get_attribute("id")
    if eid:
        lab = page.query_selector(f'label[for="{eid}"]')
        if lab:
            t = (lab.inner_text() or "").strip()
            if t: return t[:90]
    # fallback: closest preceding label/th/td text via JS
    try:
        t = el.evaluate("""e => {
            let n=e, hops=0;
            while(n && hops<6){ n=n.previousElementSibling; hops++;
              if(n && n.innerText && n.innerText.trim()) return n.innerText.trim(); }
            let p=e.closest('tr'); if(p){let th=p.querySelector('th,td'); if(th) return th.innerText.trim();}
            return '';
        }""")
        return (t or "")[:90]
    except:
        return ""

with sync_playwright() as p:
    browser, page = get_ffg_page(p)
    if section:
        # click nav link whose text starts with the section name
        links = page.query_selector_all("a")
        clicked=False
        for a in links:
            try: t=(a.inner_text() or "").strip()
            except: continue
            if t.split("\n")[0].strip()==section:
                a.click(); page.wait_for_load_state("networkidle", timeout=20000)
                clicked=True; break
        print(f"[nav] {section}: {'OK' if clicked else 'NICHT GEFUNDEN'}")
    print("URL:", page.url)
    print("H1/H2:", " | ".join((h.inner_text() or '').strip() for h in page.query_selector_all("h1,h2")[:4]))
    print("\n=== FELDER ===")
    for el in page.query_selector_all("input, textarea, select"):
        typ = (el.get_attribute("type") or el.evaluate("e=>e.tagName.toLowerCase()"))
        if typ in ("hidden","image"): continue
        name = el.get_attribute("name") or ""
        eid = el.get_attribute("id") or ""
        if not el.is_visible(): continue
        val = (el.input_value() if typ not in ("checkbox","radio","button","submit") else (el.get_attribute("value") or "")) if el else ""
        checked = el.is_checked() if typ in ("checkbox","radio") else ""
        lab = label_for(page, el)
        print(f"[{typ}] id={eid[:40]} | label={lab!r} | val={str(val)[:50]!r} {('checked='+str(checked)) if typ in ('checkbox','radio') else ''}")
    print("\n=== BUTTONS ===")
    for b in page.query_selector_all("input[type=submit], input[type=button], button, a.button"):
        if not b.is_visible(): continue
        t=(b.get_attribute("value") or b.inner_text() or "").strip()
        if t: print(" -", t[:50])
