"""Observe what the SoundCloud upload UI actually calls. Creates no track.

`POST /tracks` answers 400 with an empty error list from both transports, which
means our request shape is wrong rather than blocked. The only reliable way to
learn the right shape is to watch SoundCloud's own client make it.

## The correction that made this work

The first version attached the file to `page` and reported "file inputs on
page: 0", which got read as "the upload form does not render" — and sent a
whole investigation after a consent dialog. The form renders fine; it lives in
a NESTED same-origin iframe (`/n/upload?…&embedded=crossfade&v2_layout=true`)
inside a `webiIframe`. Requests must be watched on the CONTEXT, not the page,
for the same reason: a frame's fetches never surface on the parent's `request`
event.

Nothing is saved, so no track is created — but the page will legitimately push
the probe's bytes to S3 on its own, which is why the probe is one second of
sine and not a record.
"""
import json
import sys
from pathlib import Path

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

PROBE = Path(sys.argv[1])
OUT = Path(sys.argv[2]) if len(sys.argv) > 2 else None
seen: list[dict] = []

INTERESTING = ("api-v2.soundcloud.com", "api.soundcloud.com",
               "api-mobile.soundcloud.com")
# Telemetry drowns the signal: /me?client_id… analytics batches fire constantly
# and say nothing about track creation.
NOISE = ("/me?", "/me/", "smartnudges", "/events", "/gate", "/pageview")


def note(req):
    url = req.url
    if not any(h in url for h in INTERESTING):
        return
    if req.method == "GET" or any(n in url for n in NOISE):
        return
    body = None
    try:
        body = req.post_data
    except Exception:
        pass
    seen.append({"method": req.method, "url": url.split("?")[0],
                 "body": (body or "")[:2000],
                 "frame": (req.frame.url or "")[:60] if req.frame else ""})


with Browser() as b:
    b.open()
    consent.ensure(b.page, policy="reject")
    b.require_login()

    # Listen on the CONTEXT so nested-frame traffic is included.
    b.ctx.on("request", note)

    b.page.goto("https://soundcloud.com/upload", wait_until="domcontentloaded")
    frame = b.upload_frame()
    if frame is None:
        print("no frame carries a file input — the form really is absent this time")
        for f in b.page.frames:
            print("   frame:", (f.url or "")[:100])
        sys.exit(1)
    print(f"upload form found in frame: {frame.url[:80]}")

    frame.locator('input[type="file"]').first.set_input_files(str(PROBE))
    print("attached probe; watching for the finalize call…")
    b.page.wait_for_timeout(20000)

    print("\n--- controls in the upload frame:")
    for sel in ('input[name]', 'button', '[role="button"]'):
        loc = frame.locator(sel)
        for i in range(min(loc.count(), 30)):
            el = loc.nth(i)
            try:
                if not el.is_visible():
                    continue
                txt = (el.get_attribute("name") or el.inner_text() or "").strip()
                if txt:
                    print(f"  {sel:<18} {txt[:60]!r}")
            except Exception:
                pass

    print(f"\n--- {len(seen)} non-GET api request(s), telemetry excluded:")
    for r in seen:
        print(f"  {r['method']} {r['url']}")
        if r["body"]:
            print(f"      {r['body'][:500]}")

if OUT:
    OUT.write_text(json.dumps(seen, indent=1) + "\n")
    print(f"\nwrote {OUT}")
