"""Does SoundCloud's LEGACY uploader still exist, and does it offer Private?

The v2 form is public-only: its radios are geo (worldwide/exclusiveRegions/
blockedRegions) and licensing (all-rights-reserved/commons), and the word
"private" appears nowhere. PLN asked for a private album upload, and
upload-public-then-PUT-private leaves a window where 14 tracks with
unadjudicated sample rights are world-readable.

The form frame is served as /n/upload?...&v2_layout=true, so the obvious
question is whether v2_layout=false still renders the older form that had a
Public/Private choice. Uploads nothing.
"""
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])
CANDIDATES = [
    "https://soundcloud.com/n/upload?v2_layout=false",
    "https://soundcloud.com/n/upload",
    "https://soundcloud.com/upload?v2_layout=false",
]

SCAN = """() => {
  const t = document.body.innerText || '';
  return {
    priv: /privat/i.test(t),
    pub: /public/i.test(t),
    lines: t.split('\\n').filter(l => /privat|public|who can|visib/i.test(l))
             .map(l => l.trim().slice(0, 80)).slice(0, 10),
    radios: [...document.querySelectorAll('input[type=radio]')]
              .map(r => r.value || '(no value)'),
    selects: [...document.querySelectorAll('select')].map(s =>
              [...s.options].map(o => o.value).join('|').slice(0, 60)),
    files: document.querySelectorAll('input[type=file]').length,
  };
}"""

with Browser() as b:
    b.open()
    consent.ensure(b.page, policy="reject")
    b.require_login()
    for url in CANDIDATES:
        print(f"\n=== {url}")
        try:
            b.page.goto(url, wait_until="domcontentloaded", timeout=45000)
        except Exception as e:
            print("   goto failed:", str(e).splitlines()[0][:70])
            continue
        b.page.wait_for_timeout(5000)
        print("   landed on:", b.page.url[:90])
        # The form may be in this document or nested one deeper.
        target = None
        for f in b.page.frames:
            try:
                if f.locator('input[type="file"]').count():
                    target = f
                    break
            except Exception:
                pass
        if target is None:
            print("   no file input in any frame")
            continue
        print("   file input frame:", target.url[:80])
        target.locator('input[type="file"]').first.set_input_files(str(PROBE))
        b.page.wait_for_timeout(13000)
        d = target.evaluate(SCAN)
        print(f"   mentions private: {d['priv']}   radios: {d['radios']}")
        if d["selects"]:
            print("   selects:", d["selects"])
        for line in d["lines"]:
            print("     |", line)
        if d["priv"]:
            print("   *** PRIVATE AVAILABLE HERE ***")
            break
