"""Enumerate EVERY control on SoundCloud's upload form, so the driver is written
against what is there rather than what I imagine.

Attaches a 1-second probe and dumps inputs, selects, radios, switches, buttons
and their labels from the nested `/n/upload` frame. Stops before clicking
Upload, so no track is created — SoundCloud will push the probe's bytes to S3 on
its own, which is why the probe is a sine and not a record.

Three earlier guesses at `POST /tracks` all failed, and the last two blind spots
here were a frame we never looked in and a modal we never dismissed. So: look.
"""
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

DUMP_JS = """() => {
  const out = [];
  const label = (el) => {
    if (el.getAttribute('aria-label')) return el.getAttribute('aria-label');
    if (el.id) {
      const l = document.querySelector(`label[for="${el.id}"]`);
      if (l) return l.innerText.trim().slice(0, 50);
    }
    const l = el.closest('label');
    if (l) return l.innerText.trim().slice(0, 50);
    return '';
  };
  for (const el of document.querySelectorAll(
      'input, select, textarea, [role=switch], [role=radio], [role=checkbox], [contenteditable=true]')) {
    const r = el.getBoundingClientRect();
    out.push({
      tag: el.tagName.toLowerCase(),
      type: el.type || el.getAttribute('role') || '',
      name: el.name || '',
      id: el.id || '',
      value: (el.value || '').slice(0, 40),
      checked: el.checked ?? el.getAttribute('aria-checked') ?? null,
      label: label(el),
      visible: r.width > 0 && r.height > 0,
    });
  }
  const btns = [];
  for (const el of document.querySelectorAll('button, [role=button], a[href]')) {
    const r = el.getBoundingClientRect();
    if (!(r.width > 0 && r.height > 0)) continue;
    btns.push({
      text: (el.innerText || el.getAttribute('aria-label') || '').trim().slice(0, 60),
      cls: (el.className || '').toString().slice(0, 45),
      disabled: el.disabled ?? null,
    });
  }
  return {controls: out, buttons: btns,
          text: (document.body.innerText || '').replace(/\\n{2,}/g, '\\n').slice(0, 1500)};
}"""

with Browser() as b:
    b.open()
    consent.ensure(b.page, policy="reject")
    b.require_login()
    b.page.goto("https://soundcloud.com/upload", wait_until="domcontentloaded")
    frame = b.upload_frame()
    if frame is None:
        sys.exit("no frame carries a file input")
    print(f"form frame: {frame.url[:70]}\n")

    frame.locator('input[type="file"]').first.set_input_files(str(PROBE))
    b.page.wait_for_timeout(15000)

    d = frame.evaluate(DUMP_JS)
    print("--- controls ---")
    for c in d["controls"]:
        if not c["visible"] and c["type"] != "file":
            continue
        print(f"  {c['tag']:<15} type={c['type']:<14} name={c['name']:<16} "
              f"id={c['id'][:18]:<18} checked={str(c['checked'])[:5]:<5} "
              f"{c['label'][:34]!r}")
    print("\n--- buttons ---")
    for x in d["buttons"]:
        print(f"  {str(x['disabled'])[:5]:<5} {x['text']!r}")
    print("\n--- frame text ---")
    for line in d["text"].splitlines():
        if line.strip():
            print("   |", line.strip()[:96])

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