FIXTURES="$BATS_TEST_DIRNAME/../fixtures"

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

setup() {
    export LIB_DIR="$LIBDIR"
    load '../../package/kit-busrouter/files/usr/lib/busrouter/telemetry.sh'
}

@test "gps_fix parse: 3D fix returns lat lon fix_quality=3" {
    run _gps_parse < "$FIXTURES/gps-fix.txt"
    [ "$status" -eq 0 ]
    lat=$(echo "$output" | awk '{print $1}')
    lon=$(echo "$output" | awk '{print $2}')
    fix=$(echo "$output" | awk '{print $3}')
    [ "$lat" = "40.712776" ]
    [ "$lon" = "-74.005974" ]
    [ "$fix" -eq 3 ]
}

@test "gps_fix parse: no-fix response exits 1" {
    run _gps_parse < "$FIXTURES/gps-nofix.txt"
    [ "$status" -ne 0 ]
    [ -z "$output" ]
}

@test "gps_fix parse: empty input exits 1" {
    run _gps_parse < /dev/null
    [ "$status" -ne 0 ]
    [ -z "$output" ]
}

# --- Task 5.2: telemetry collect + POST ---

@test "telemetry_collect: output contains required JSON keys" {
    run telemetry_collect
    [ "$status" -eq 0 ]
    echo "$output" | grep -q '"device_id"'
    echo "$output" | grep -q '"timestamp"'
    echo "$output" | grep -q '"gps"'
    echo "$output" | grep -q '"wan"'
    echo "$output" | grep -q '"starlink"'
    echo "$output" | grep -q '"sim_slot"'
    echo "$output" | grep -q '"uptime"'
}

@test "telemetry_send: buffers payload when curl fails" {
    mkdir -p "$BATS_TMPDIR/tel_stub"
    printf '#!/bin/sh\nexit 7\n' > "$BATS_TMPDIR/tel_stub/curl"
    chmod +x "$BATS_TMPDIR/tel_stub/curl"
    export PATH="$BATS_TMPDIR/tel_stub:$PATH"
    export TELEMETRY_HUB="http://10.88.0.1:8080/api/telemetry"
    export TELEMETRY_BUFFER_DIR="$BATS_TMPDIR/tel_buf"
    rm -rf "$TELEMETRY_BUFFER_DIR"
    run telemetry_send
    [ -d "$TELEMETRY_BUFFER_DIR" ]
    buf_count=$(ls "$TELEMETRY_BUFFER_DIR"/*.json 2>/dev/null | wc -l)
    [ "$buf_count" -ge 1 ]
}

@test "telemetry_flush: posts and removes buffered file on success" {
    mkdir -p "$BATS_TMPDIR/tel_stub2"
    printf '#!/bin/sh\necho 200\n' > "$BATS_TMPDIR/tel_stub2/curl"
    chmod +x "$BATS_TMPDIR/tel_stub2/curl"
    export PATH="$BATS_TMPDIR/tel_stub2:$PATH"
    export TELEMETRY_HUB="http://10.88.0.1:8080/api/telemetry"
    export TELEMETRY_BUFFER_DIR="$BATS_TMPDIR/tel_flush_buf"
    mkdir -p "$TELEMETRY_BUFFER_DIR"
    echo '{"test":1}' > "$TELEMETRY_BUFFER_DIR/1234567890_test.json"
    run telemetry_flush
    [ "$status" -eq 0 ]
    [ ! -f "$TELEMETRY_BUFFER_DIR/1234567890_test.json" ]
}
