#!/usr/bin/env bash
set -euo pipefail

# shellcheck source=../lib/common.sh
source "$(dirname "$0")/../lib/common.sh"

cd "$LM_ROOT"
PORT="${TEST_PORT:-$LM_TEST_PORT}"
BASE="http://127.0.0.1:${PORT}"
BIN="${LM_ROOT}/build/lidar_manager_web"
DATA_DIR="$(mktemp -d)"
SERVER_PID=""

free_port "$PORT"
sleep 0.2

cleanup() {
  if [[ -n "$SERVER_PID" ]] && kill -0 "$SERVER_PID" 2>/dev/null; then
    kill "$SERVER_PID" 2>/dev/null || true
    wait "$SERVER_PID" 2>/dev/null || true
  fi
  rm -rf "$DATA_DIR"
}
trap cleanup EXIT

echo "==> Configure & build (BUILD_TESTING=ON)"
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
cmake --build build -j

echo "==> C++ unit tests (GTest)"
./build/lidar_manager_tests

echo "==> Prepare isolated data directory"
cp -a tests/fixtures/data/. "$DATA_DIR/"
mkdir -p "$DATA_DIR/models"

echo "==> Start server on port $PORT"
"$BIN" "$PORT" "$LM_ROOT/www" "$DATA_DIR/state.json" >"$DATA_DIR/server.log" 2>&1 &
SERVER_PID=$!

if ! wait_for_health "$BASE" 30; then
  if ! kill -0 "$SERVER_PID" 2>/dev/null; then
    echo "Server exited early:" >&2
    cat "$DATA_DIR/server.log" >&2 || true
  else
    echo "Server did not become ready on $BASE" >&2
    cat "$DATA_DIR/server.log" >&2 || true
  fi
  exit 1
fi

echo "==> API smoke tests"
"$LM_SCRIPTS/test/smoke.sh" "$BASE"

if command -v python3 >/dev/null 2>&1; then
  echo "==> Python integration tests (pytest)"
  if ! python3 -c "import pytest" 2>/dev/null; then
    python3 -m pip install --user -q -r tests/requirements.txt
  fi
  TEST_BASE_URL="$BASE" python3 -m pytest tests/test_api_integration.py -q
else
  echo "==> Skipping pytest (python3 not found)"
fi

echo
echo "All tests passed."
