#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
harness="$repo_dir/config/dot/quickshell/audio-streams-harness.qml"
state_home="$(mktemp -d /tmp/panama-application-volume-state.XXXXXX)"
shell_log="$state_home/quickshell.log"
harness_pid=""

fail() {
    printf 'application volume contract: %s\n' "$1" >&2
    [[ -s "$shell_log" ]] && sed -n '1,160p' "$shell_log" >&2
    exit 1
}

instances_for_harness() {
    qs list --all 2>/dev/null | awk -v expected="$harness" '
        /^Instance / { pid = "" }
        /^[[:space:]]*Process ID:/ { pid = $3 }
        /^[[:space:]]*Config path:/ {
            path = $0
            sub(/^[[:space:]]*Config path: /, "", path)
            if (path == expected && pid ~ /^[0-9]+$/) print pid
        }
    '
}

cleanup() {
    if [[ "$harness_pid" =~ ^[0-9]+$ ]] && kill -0 "$harness_pid" 2>/dev/null; then
        kill "$harness_pid" 2>/dev/null || true
        for _ in $(seq 1 40); do
            kill -0 "$harness_pid" 2>/dev/null || break
            sleep 0.05
        done
    fi
    rm -rf "$state_home"
}
trap cleanup EXIT

qs_for_harness() {
    if [[ "$harness_pid" =~ ^[0-9]+$ && "${1:-}" == "ipc" ]]; then
        XDG_STATE_HOME="$state_home" qs -p "$harness" ipc --pid "$harness_pid" "${@:2}"
    else
        XDG_STATE_HOME="$state_home" qs -p "$harness" "$@"
    fi
}

qs_for_harness --daemonize >"$shell_log" 2>&1 || fail 'isolated harness did not launch'
for _ in $(seq 1 50); do
    harness_pid="$(instances_for_harness | head -1)"
    if [[ "$harness_pid" =~ ^[0-9]+$ ]] \
        && qs_for_harness ipc show 2>/dev/null | rg -q '^target application-volume-test$'; then
        break
    fi
    sleep 0.1
done
[[ "$harness_pid" =~ ^[0-9]+$ ]] || fail 'isolated harness process did not start'
qs_for_harness ipc show 2>/dev/null | rg -q '^target application-volume-test$' \
    || fail 'application-volume-test IPC target did not register'

summary="$(qs_for_harness ipc call application-volume-test summary)"
expected_groups='[
  {"key":"org.chromium.Chromium","label":"Chromium","icon":"chromium","count":2},
  {"key":"spotify","label":"Spotify","icon":"audio-x-generic-symbolic","count":1},
  {"key":"node:99","label":"Unknown application","icon":"audio-x-generic-symbolic","count":1}
]'
jq -e --argjson expected "$expected_groups" \
    '.groups == $expected and (.chromiumVolume - 0.6 | fabs) < 0.000001 and .chromiumMuted == false' \
    <<<"$summary" >/dev/null || fail "unexpected grouping summary: $summary"

volume_result="$(qs_for_harness ipc call application-volume-test mutateVolume)"
jq -e '.changed == true and .volumes == [0.7, 0.7] and .muted == [false, false]' \
    <<<"$volume_result" >/dev/null || fail "volume mutation did not reach every stream: $volume_result"

mute_result="$(qs_for_harness ipc call application-volume-test mutateMute)"
jq -e '.changed == true and .muted == [true, true]' <<<"$mute_result" >/dev/null \
    || fail "mute mutation did not reach every stream: $mute_result"

service_summary="$(qs_for_harness ipc call application-volume-test serviceSummary)"
jq -e '.count >= 0 and .validTypes == true' <<<"$service_summary" >/dev/null \
    || fail "live service exposed invalid playback groups: $service_summary"

invalid_result="$(qs_for_harness ipc call application-volume-test invalidMutations)"
jq -e '.nullVolume == false and .emptyMute == false' <<<"$invalid_result" >/dev/null \
    || fail "service mutators accepted missing audio nodes: $invalid_result"

if rg -n 'ReferenceError|TypeError|Binding loop|Cannot assign|PwObjectTracker' "$shell_log"; then
    fail 'isolated harness emitted a QML runtime error'
fi

printf 'application volume contract: PASS\n'
