#!/usr/bin/env bash

set -euo pipefail

repo_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
bluetooth="$repo_dir/config/dot/quickshell/modules/quicksettings/BluetoothList.qml"

rg -q 'const shouldDiscover = root\.active && root\.adapter\.enabled' "$bluetooth" || {
    printf 'bluetooth discovery contract: desired state is not calculated idempotently\n' >&2
    exit 1
}
rg -q 'shouldDiscover && !root\.adapter\.discovering' "$bluetooth" || {
    printf 'bluetooth discovery contract: redundant BlueZ starts are not guarded\n' >&2
    exit 1
}
rg -q '!shouldDiscover && root\.discoveryOwned && root\.adapter\.discovering' "$bluetooth" || {
    printf 'bluetooth discovery contract: the picker may stop discovery it does not own\n' >&2
    exit 1
}
! rg -q 'Component\.onCompleted: root\.syncDiscovery' "$bluetooth" || {
    printf 'bluetooth discovery contract: inactive construction still writes BlueZ state\n' >&2
    exit 1
}
rg -Uq 'onAdapterChanged:[^{\n]*\{[^}]*if \(root\.active\)' "$bluetooth" || {
    printf 'bluetooth discovery contract: adapter changes are not gated by an open panel\n' >&2
    exit 1
}
rg -Uq 'Component\.onDestruction:[^{\n]*\{[^}]*root\.discoveryOwned' "$bluetooth" || {
    printf 'bluetooth discovery contract: owned discovery is not released on destruction\n' >&2
    exit 1
}

printf 'bluetooth discovery contract: PASS\n'
