/* ── the service, the focus stack and the noisy receiver ──────────────
 *  Three things `dumpsys` can say about the media session that no page and
 *  no notification can. ALL THREE ARE ADVISORY: they print on every run and
 *  fail nothing. None of these dump formats has ever been read back from
 *  this phone, and a format surprise must not turn into a false red on a
 *  walk that is otherwise green.
 *
 *  What they are for is the morning after a change to how the service is
 *  made. `fgs` says whether the service exists at all and whether media3
 *  promoted it; `focus` whether the audio-focus request this plugin still
 *  makes BY HAND is in the system's stack, which is the direct regression
 *  guard for "another app takes the output and we pause"; `noisy` whether
 *  the becoming-noisy receiver is REGISTERED, which is the half of
 *  "headphones out pauses" that a creation-path change actually breaks.
 *
 *  Neither of the last two proves the pause itself, and nothing here can:
 *  ACTION_AUDIO_BECOMING_NOISY is a protected broadcast, so `am broadcast`
 *  from the shell uid is refused outright, and the receiver is registered
 *  RECEIVER_NOT_EXPORTED besides. Those two are Kyle's hands. */
function mediaPlumbing() {
    const out = { fgs: "", focus: "", noisy: "" };
    try {
        const svc = adb("shell", "dumpsys", "activity", "services", "com.soulstream.app").toString();
        const at = svc.indexOf("com.soulstream.mediasession.MediaService");
        out.fgs = at < 0 ? "absent" : (/isForeground=true/.test(svc.slice(at, at + 6000)) ? "foreground" : "created");
    } catch (e) { out.fgs = "ERR " + e.message; }
    try {
        const audio = adb("shell", "dumpsys", "audio").toString();
        out.focus = /pack: com\.soulstream\.app/.test(audio) ? "held" : "not in the stack";
    } catch (e) { out.focus = "ERR " + e.message; }
    try {
        const bc = adb("shell", "dumpsys", "activity", "broadcasts").toString();
        /* each registered receiver is one `ReceiverList{...}` block with its
           package on the first line and its filters under it; the windows
           keep a match from wandering into the next block */
        const ours = bc.split("ReceiverList{").filter((b) =>
            /com\.soulstream\.app/.test(b.slice(0, 400)) && /AUDIO_BECOMING_NOISY/.test(b.slice(0, 2000)));
        out.noisy = ours.length ? "registered" : "not found";
    } catch (e) { out.noisy = "ERR " + e.message; }
    return out;
}

