"""Find and operate SoundCloud's privacy control — a MUI Select, not a radio.

My earlier probes concluded "the v2 uploader is public-only". That was wrong, and
the reason is worth keeping: the control is a **MUI `Select`**, whose options are
rendered into a PORTAL only after the trigger is clicked. A closed MUI menu has
no options in the DOM at all, so sweeping `input[type=radio]`,
`input[type=checkbox]` and `select` finds the geo and licensing radios and then
truthfully reports that no privacy control exists. PLN read the real markup and
handed it over:

    <li role="option" aria-label="Private" data-value="Private"
        class="MuiButtonBase-root MuiMenuItem-root …">
      Private / "Track is not discoverable. Only people with private link can
      view and listen."

Third time in this project the instrument was the broken part rather than the
rig. The generalisable rule: a component library's Select is not `<select>`, and
"the control is absent" and "the control is unmounted" look identical to a DOM
sweep.

So: open the menu, enumerate the options, pick one, and CONFIRM the trigger
changed. Uploads nothing — never touches the Upload button.
"""
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])
WANT = sys.argv[2] if len(sys.argv) > 2 else "Private"

TRIGGERS = ['[role="combobox"]', ".MuiSelect-select"]

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 upload frame")
    frame.locator('input[type="file"]').first.set_input_files(str(PROBE))
    b.page.wait_for_timeout(14000)

    print("--- candidate triggers in the form frame ---")
    for sel in TRIGGERS:
        try:
            loc = frame.locator(sel)
            n = loc.count()
        except Exception as e:
            print(f"  {sel:<26} ERR {str(e).splitlines()[0][:40]}")
            continue
        print(f"  {sel:<26} {n} match(es)")
        for i in range(min(n, 8)):
            el = loc.nth(i)
            try:
                txt = (el.inner_text() or "").replace("\n", " ").strip()[:44]
                print(f"      [{i}] visible={el.is_visible()}  {txt!r}")
            except Exception:
                pass

    # The sharing Select is the visible combobox currently reading "Public".
    combo = frame.locator('[role="combobox"], .MuiSelect-select')
    target = None
    for i in range(combo.count()):
        el = combo.nth(i)
        try:
            if el.is_visible() and "public" in (el.inner_text() or "").lower():
                target = el
                break
        except Exception:
            continue
    if target is None:
        sys.exit("\nno visible combobox reading 'Public' — see dump above")

    print(f"\nopening the sharing Select (reads {target.inner_text()!r})")
    target.click()
    b.page.wait_for_timeout(1500)

    opts = frame.locator('li[role="option"]')
    print(f"--- {opts.count()} option(s) now in the DOM (portal-rendered) ---")
    for i in range(opts.count()):
        el = opts.nth(i)
        label = (el.inner_text() or "").replace("\n", " | ")[:72]
        print(f"  data-value={el.get_attribute('data-value')!r:<12} "
              f"selected={el.get_attribute('aria-selected')!r:<7} {label!r}")

    pick = frame.locator(f'li[role="option"][data-value="{WANT}"]')
    if not pick.count():
        sys.exit(f"\nno option with data-value={WANT!r}")
    pick.first.click()
    b.page.wait_for_timeout(1500)
    now = (target.inner_text() or "").replace("\n", " ").strip()
    print(f"\ntrigger now reads: {now!r}")
    print("VERIFIED" if WANT.lower() in now.lower()
          else "NOT APPLIED — the click did not take")
