#!/usr/bin/env bash
# tests/run-ipc-fixtures: Layer 1 IPC fixture tests (D-030)
# Runs Rust serialization round-trip tests + GDScript fixture validation.
# GDScript side is skipped if client/tests/test_ipc_fixtures.gd doesn't exist yet (#271).
# Exit: 0 = all pass, non-zero = any failure
# Stdout: {"suite":"ipc-fixtures","total":N,"passed":N,"failed":N,"duration_ms":N}
set -euo pipefail

FILTER=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        --filter) FILTER="${2:-}"; shift 2 ;;
        --filter=*) FILTER="${1#--filter=}"; shift ;;
        *) echo "Unknown argument: $1" >&2; exit 2 ;;
    esac
done

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

_extract_num() {
    local haystack="$1" pattern="$2"
    echo "$haystack" | grep -oE "[0-9]+ $pattern" | grep -oE '^[0-9]+' || echo 0
}

_parse_nextest_summary() {
    local tmpout="$1"
    local summary total passed failed
    summary=$(grep -E "^\s*(Summary|Finished)" "$tmpout" | tail -1 || true)
    if [[ -n "$summary" ]]; then
        total=$(_extract_num "$summary" "tests? run")
        passed=$(_extract_num "$summary" "passed")
        failed=$(_extract_num "$summary" "failed")
    else
        total=0; passed=0; failed=0
    fi
    echo "$total $passed $failed"
}

# --- Layer 1a: Rust serialization tests ---
START_MS=$(date +%s%3N)

cd "$REPO_ROOT/server"
TMPOUT=$(mktemp)
NEXTEST_ARGS=(nextest run --color never --test serialization)
[[ -n "$FILTER" ]] && NEXTEST_ARGS+=(-E "test(~${FILTER})")

set +e
cargo "${NEXTEST_ARGS[@]}" 2>&1 | tee "$TMPOUT" >&2
RUST_EXIT=${PIPESTATUS[0]}
set -e

read -r RUST_TOTAL RUST_PASSED RUST_FAILED < <(_parse_nextest_summary "$TMPOUT")
rm -f "$TMPOUT"

# --- Layer 1b: GDScript fixture tests (optional until #271 lands) ---
GDS_FIXTURE="$REPO_ROOT/client/tests/test_ipc_fixtures.gd"
GDS_TOTAL=0; GDS_PASSED=0; GDS_FAILED=0; GDS_EXIT=0

if [[ -f "$GDS_FIXTURE" ]]; then
    GODOT=$(command -v godot4 2>/dev/null || command -v godot 2>/dev/null || echo "")
    if [[ -z "$GODOT" ]]; then
        echo "Warning: test_ipc_fixtures.gd found but godot not in PATH — skipping GDScript layer" >&2
    else
        GDTMP=$(mktemp)
        set +e
        "$GODOT" --headless --path "$REPO_ROOT/client" \
            -s res://addons/gdUnit4/bin/GdUnitCmdTool.gd \
            --ignoreHeadlessMode -c \
            -a res://tests/test_ipc_fixtures.gd \
            2>&1 | tee "$GDTMP" >&2
        GDS_EXIT=${PIPESTATUS[0]}
        set -e

        STATS=$(grep -oE "[0-9]+ test cases \| [0-9]+ errors \| [0-9]+ failures" "$GDTMP" || true)
        if [[ -n "$STATS" ]]; then
            GDS_TOTAL=$(echo "$STATS" | grep -oE '^[0-9]+' | awk '{s+=$1} END {print s}')
            ERRS=$(echo "$STATS" | grep -oE '[0-9]+ errors' | grep -oE '^[0-9]+' | awk '{s+=$1} END {print s}')
            FAILS=$(echo "$STATS" | grep -oE '[0-9]+ failures' | grep -oE '^[0-9]+' | awk '{s+=$1} END {print s}')
            GDS_FAILED=$(( ${ERRS:-0} + ${FAILS:-0} ))
            GDS_PASSED=$(( GDS_TOTAL - GDS_FAILED ))
        fi
        rm -f "$GDTMP"
    fi
fi

END_MS=$(date +%s%3N)
DURATION_MS=$((END_MS - START_MS))

TOTAL=$(( RUST_TOTAL + GDS_TOTAL ))
PASSED=$(( RUST_PASSED + GDS_PASSED ))
FAILED=$(( RUST_FAILED + GDS_FAILED ))

# Overall exit: fail if either side failed
EXIT_CODE=$(( RUST_EXIT != 0 || GDS_EXIT != 0 ? 1 : 0 ))

printf '{"suite":"ipc-fixtures","total":%d,"passed":%d,"failed":%d,"duration_ms":%d}\n' \
    "$TOTAL" "$PASSED" "$FAILED" "$DURATION_MS"
exit $EXIT_CODE
