"""Open the real upload form and WATCH what PLN clicks.

My probes concluded the v2 uploader is public-only: its radios are geo and
licensing, and "private" appears nowhere in the frame text. PLN says there is a
private option and offered to point at it — which is faster and more reliable
than another round of my guessing, and this is the third time in this project
that the instrument was the thing that was wrong.

So: attach a probe file (the metadata form only renders once audio is attached),
hold the window open, and poll the form state. Whenever a control's checked-state
or the visible text changes, print the delta. PLN clicks Private; the script
reports exactly which element that is, and the driver gets written against it.

Uploads nothing — never touches the Upload button.
"""
import sys
import time
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])
HOLD = float(sys.argv[2]) if len(sys.argv) > 2 else 420.0

STATE = """() => {
  const sel = (el) => {
    if (el.id) return '#' + el.id;
    if (el.name) return `${el.tagName.toLowerCase()}[name="${el.name}"]`;
    const p = el.closest('[class]');
    return `${el.tagName.toLowerCase()}[value="${el.value}"]`
           + (p ? ` in .${(p.className||'').toString().split(/\\s+/)[0]}` : '');
  };
  const near = (el) => {
    let n = el, best = '', d = 0;
    while (n && d < 7) {
      const t = (n.innerText || '').replace(/\\s+/g, ' ').trim();
      if (t.length > best.length) best = t;
      if (best.length > 25) break;
      n = n.parentElement; d++;
    }
    return best.slice(0, 90);
  };
  const controls = {};
  document.querySelectorAll(
      'input[type=radio], input[type=checkbox], [role=switch], select'
  ).forEach((el, i) => {
    const key = `${i}:${sel(el)}:${el.value || ''}`;
    controls[key] = {
      on: el.type === 'checkbox' || el.type === 'radio'
            ? el.checked
            : (el.getAttribute('aria-checked') ?? el.value),
      label: near(el),
    };
  });
  return {controls, text: (document.body.innerText || '')};
}"""


def diff(a, b):
    out = []
    for k, v in b["controls"].items():
        old = a["controls"].get(k)
        if old is None:
            out.append(f"NEW    {k}  on={v['on']}  {v['label']!r}")
        elif old["on"] != v["on"]:
            out.append(f"CHANGED {k}  {old['on']} -> {v['on']}  {v['label']!r}")
    for k in a["controls"]:
        if k not in b["controls"]:
            out.append(f"GONE   {k}")
    ta, tb = set(a["text"].splitlines()), set(b["text"].splitlines())
    for line in list(tb - ta)[:8]:
        if line.strip():
            out.append(f"TEXT+  {line.strip()[:80]!r}")
    return out


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)

    prev = frame.evaluate(STATE)
    print(f"form ready — {len(prev['controls'])} controls tracked.\n"
          f"Click the PRIVATE option (open any collapsed section if it is in one).\n"
          f"Watching for {HOLD:.0f}s. Do NOT press Upload — this window will "
          f"close on its own.\n", flush=True)

    deadline = time.time() + HOLD
    while time.time() < deadline:
        b.page.wait_for_timeout(2500)
        try:
            cur = frame.evaluate(STATE)
        except Exception as e:
            print("  (frame went away:", str(e).splitlines()[0][:60], ")", flush=True)
            break
        d = diff(prev, cur)
        if d:
            print(f"[+{HOLD - (deadline - time.time()):.0f}s]", flush=True)
            for line in d:
                print("   ", line, flush=True)
            prev = cur
    print("\ndone watching", flush=True)
