#!/usr/bin/env bash
# tests/run-ipc-integration: Layer 3 real-subprocess integration tests (D-030)
# Spawns the server binary as a real child process, runs IPC round-trip.
# Also invokes tests/run-ipc-benchmark when that script exists (#342).
# Exit: 0 = all pass, non-zero = any failure
# Stdout: {"suite":"ipc-integration","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)"
cd "$REPO_ROOT/server"

START_MS=$(date +%s%3N)
TMPOUT=$(mktemp)

NEXTEST_ARGS=(nextest run --color never --test layer3)
[[ -n "$FILTER" ]] && NEXTEST_ARGS+=(-E "test(~${FILTER})")

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

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

SUMMARY=$(grep -E "^\s*(Summary|Finished)" "$TMPOUT" | tail -1 || true)
TOTAL=0; PASSED=0; FAILED=0
if [[ -n "$SUMMARY" ]]; then
    TOTAL=$(_extract_num "$SUMMARY" "tests? run")
    PASSED=$(_extract_num "$SUMMARY" "passed")
    FAILED=$(_extract_num "$SUMMARY" "failed")
fi
rm -f "$TMPOUT"

# Run IPC benchmark if it exists (#342 — requires handshake from #555/#556)
BENCH_SCRIPT="$REPO_ROOT/tests/run-ipc-benchmark"
BENCH_EXIT=0
if [[ -x "$BENCH_SCRIPT" ]]; then
    BENCH_ARGS=()
    [[ -n "$FILTER" ]] && BENCH_ARGS+=(--filter "$FILTER")
    set +e
    "$BENCH_SCRIPT" "${BENCH_ARGS[@]}" >&2
    BENCH_EXIT=$?
    set -e
    if [[ $BENCH_EXIT -ne 0 ]]; then
        FAILED=$(( FAILED + 1 ))
        TOTAL=$(( TOTAL + 1 ))
    else
        PASSED=$(( PASSED + 1 ))
        TOTAL=$(( TOTAL + 1 ))
    fi
fi

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

EXIT_CODE=$(( LAYER3_EXIT != 0 || BENCH_EXIT != 0 ? 1 : 0 ))

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