LIBDIR="$(cd "$BATS_TEST_DIRNAME/../.."/package/kit-busrouter/files/usr/lib/busrouter && pwd)"

setup() {
    export LIB_DIR="$LIBDIR"
    export STATE_DIR="$BATS_TMPDIR/daemon_state"
    rm -rf "$STATE_DIR"
    mkdir -p "$STATE_DIR"
    export SCORE_SAMPLES=3
    export CELL_IFACE=rmnet_mhi0 CELL_MBR=modem_0001
    export ETH_IFACE=eth0 ETH_MBR=wan
    export INTERVAL=30
    # Load all libs (daemon.sh's while loop is guarded by case "${0##*/}" so safe to load)
    load '../../package/kit-busrouter/files/usr/lib/busrouter/lib-decide.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/lib-score.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/metrics-net.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/speedtest.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/modem-sim.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/starlink.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/wan-mwan.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/telemetry.sh'
    load '../../package/kit-busrouter/files/usr/lib/busrouter/daemon.sh'
}

@test "daemon.sh loads without error and does not start loop" {
    run true
    [ "$status" -eq 0 ]
    # If we reach here, the load in setup() did not hang -> loop guard works
}

@test "_score_history_update: primes from default 50 50 50 and appends new score" {
    run _score_history_update "modem_0001" 70
    [ "$status" -eq 0 ]
    echo "$output" | grep -qE '^50 50 70$'
}

@test "_score_history_update: keeps last SCORE_SAMPLES scores only" {
    export SCORE_SAMPLES=3
    _score_history_update "modem_0001" 60 >/dev/null
    _score_history_update "modem_0001" 70 >/dev/null
    _score_history_update "modem_0001" 80 >/dev/null
    run _score_history_update "modem_0001" 90
    [ "$status" -eq 0 ]
    # Should be "70 80 90" (last 3 of: 50 50 50 60 70 80 90)
    echo "$output" | grep -qE '^70 80 90$'
}

@test "_collect_wan: writes metric and score files" {
    net_probe_iface() { echo "20 5 0"; }
    speed_test_due() { return 0; }
    speed_test_iface() { echo "50.0 10.0"; }
    score_composite() { echo "75"; }
    rolling_avg() { echo "72"; }

    run _collect_wan "eth0" "wan"
    [ "$status" -eq 0 ]
    [ -f "${STATE_DIR}/metric_wan" ]
    [ -f "${STATE_DIR}/score_wan" ]
    score=$(cat "${STATE_DIR}/score_wan")
    [ "$score" -eq 72 ]
}

@test "_collect_wan: fail-open when net_probe_iface returns error" {
    net_probe_iface() { return 1; }
    speed_test_due() { return 1; }
    score_composite() { echo "0"; }
    rolling_avg() { echo "0"; }

    run _collect_wan "rmnet_mhi0" "modem_0001" "-99"
    [ "$status" -eq 0 ]
    [ -f "${STATE_DIR}/metric_modem_0001" ]
}
