#!/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"

# Over-amplification lives in Settings, and AudioStreams.js is pure JavaScript
# with no Settings import -- so the ceiling arrives as an argument. What must
# not happen is a default that quietly follows the preference: a caller that
# forgets to pass the max gets 100%, not 150%.
clamp_result="$(qs_for_harness ipc call application-volume-test clampVolume)"
jq -e '.overAmpChanged == true
    and ((.overAmp[0] - 1.4) | fabs) < 0.000001
    and (.overAmp | length) == 2 and (.overAmp[0] == .overAmp[1])
    and .overAmpMuted == [false, false]
    and .ceiling == [1.5, 1.5]
    and .defaultMax == [1, 1]
    and .floor == [0, 0]
    and .nonNumericChanged == false
    and .nonNumeric == [0.1, 0.1]' \
    <<<"$clamp_result" >/dev/null || fail "volume clamp did not honour its max parameter: $clamp_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'
