"""Why does /upload render no file input? Look at the page instead of guessing.

`session_ok()` says the session is fine and the probe says there are zero
`input[type=file]` elements, so one of them is measuring the wrong thing. The
candidate explanations are all cheap to separate by LOOKING:

  * a consent gate      -> a dialog element, or a body with scroll locked
  * a lazy React island -> the drop zone text exists but the input appears
                           only after a click
  * a shadow root       -> the input exists but `locator` cannot see it
  * a cross-origin frame-> the form is in an iframe

So: dump the main region's text, every frame, every element with a high
z-index, and count file inputs again after a click on whatever looks like the
drop zone. Uploads nothing.
"""
import sys
from pathlib import Path

sys.path.insert(0, "/home/pln/Work/Sound/tidal-ears/src")
from tidal_ears.scbrowser import Browser  # noqa: E402

with Browser() as b:
    b.open()
    b.page.goto("https://soundcloud.com/upload", wait_until="load")
    b.page.wait_for_timeout(8000)

    print("url:", b.page.url)
    print("title:", b.page.title())

    # -- 1. is anything overlaying the page, and is scroll locked? ----------
    over = b.page.evaluate("""() => {
      const out = [];
      for (const el of document.querySelectorAll('body *')) {
        const s = getComputedStyle(el);
        const z = parseInt(s.zIndex);
        if ((s.position === 'fixed' || s.position === 'absolute') && z >= 100) {
          const r = el.getBoundingClientRect();
          if (r.width > 200 && r.height > 100 && s.display !== 'none')
            out.push({tag: el.tagName, cls: (el.className || '').toString().slice(0, 60),
                      z, w: Math.round(r.width), h: Math.round(r.height)});
        }
      }
      return {overlays: out.slice(0, 12),
              bodyOverflow: getComputedStyle(document.body).overflow,
              dialogs: document.querySelectorAll('dialog,[role=dialog]').length};
    }""")
    print("\n-- overlays / scroll lock:")
    print("  body overflow:", over["bodyOverflow"], " dialogs:", over["dialogs"])
    for o in over["overlays"]:
        print(f"  z={o['z']:<6} {o['tag']:<8} {o['w']}x{o['h']}  {o['cls']!r}")

    # -- 2. frames: is the form simply somewhere else? ----------------------
    print("\n-- frames:")
    for f in b.page.frames:
        try:
            n = f.locator('input[type="file"]').count()
        except Exception:
            n = "?"
        print(f"  {n} file input(s)  {f.url[:90]}")

    # -- 3. shadow roots hide elements from ordinary selectors --------------
    deep = b.page.evaluate("""() => {
      let inputs = 0, roots = 0;
      const walk = (root) => {
        for (const el of root.querySelectorAll('*')) {
          if (el.tagName === 'INPUT' && el.type === 'file') inputs++;
          if (el.shadowRoot) { roots++; walk(el.shadowRoot); }
        }
      };
      walk(document);
      return {inputs, roots};
    }""")
    print(f"\n-- deep scan (shadow roots included): {deep['inputs']} file input(s), "
          f"{deep['roots']} shadow root(s)")

    # -- 4. what does the main region actually SAY? -------------------------
    txt = b.page.evaluate("""() => {
      const m = document.querySelector('main, #content, .l-container, body');
      return (m ? m.innerText : '').replace(/\\n{2,}/g, '\\n').slice(0, 1200);
    }""")
    print("\n-- main region text:")
    for line in txt.splitlines():
        if line.strip():
            print("   |", line.strip()[:100])

    # -- 5. does a click on the drop zone summon the input? ----------------
    for label in ("Choose files", "Choose file", "Select files", "Upload",
                  "drag and drop", "Drag and drop"):
        loc = b.page.get_by_text(label, exact=False)
        if loc.count():
            print(f"\n-- clicking {label!r} ({loc.count()} match(es))")
            try:
                loc.first.click(timeout=4000)
                b.page.wait_for_timeout(3000)
            except Exception as e:
                print("   click failed:", str(e).splitlines()[0][:100])
            print("   file inputs now:",
                  b.page.locator('input[type="file"]').count())
            break
    else:
        print("\n-- no drop-zone-looking text found at all")
