#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
LOG_DIR="$SCRIPT_DIR/logs"
mkdir -p "$LOG_DIR"

echo "=== Chat Service Test Runner ==="
echo "Log directory: $LOG_DIR"
echo ""

cleanup() {
    echo ""
    echo "=== Collecting container logs ==="
    docker compose -f "$SCRIPT_DIR/docker-compose.yml" logs chat-rpc > "$LOG_DIR/chat-rpc.log" 2>&1 || true
    docker compose -f "$SCRIPT_DIR/docker-compose.yml" logs chat-api > "$LOG_DIR/chat-api.log" 2>&1 || true
    echo "=== Stopping containers ==="
    docker compose -f "$SCRIPT_DIR/docker-compose.yml" down --remove-orphans 2>/dev/null || true
}
trap cleanup EXIT

echo "=== Step 1: Building Docker images ==="
docker compose -f "$SCRIPT_DIR/docker-compose.yml" build 2>&1 | tee "$LOG_DIR/build.log"
echo ""

echo "=== Step 2: Starting services ==="
docker compose -f "$SCRIPT_DIR/docker-compose.yml" up -d 2>&1 | tee -a "$LOG_DIR/build.log"
echo ""

echo "=== Step 3: Waiting for services to be ready ==="
for i in $(seq 1 30); do
    if curl -s http://localhost:28888 > /dev/null 2>&1 || [ $i -eq 30 ]; then
        break
    fi
    echo "  waiting... ($i/30)"
    sleep 2
done
sleep 3
echo "Services should be ready."
echo ""

echo "=== Step 4: Running WebSocket tests ==="
cd "$SCRIPT_DIR"
python3 test_ws.py 2>&1 | tee "$LOG_DIR/ws_test_stdout.log"
WS_RC=${PIPESTATUS[0]}
echo ""

echo "=== Step 5: Running WebTransport fallback tests ==="
python3 test_wt.py 2>&1 | tee "$LOG_DIR/wt_test_stdout.log"
WT_RC=${PIPESTATUS[0]}
echo ""

echo "=== Test Summary ==="
echo "WebSocket test:     $([ $WS_RC -eq 0 ] && echo 'PASSED' || echo 'FAILED')"
echo "WebTransport test:  $([ $WT_RC -eq 0 ] && echo 'PASSED' || echo 'FAILED')"
echo ""
echo "Logs saved to: $LOG_DIR/"
ls -la "$LOG_DIR/"

if [ $WS_RC -ne 0 ] || [ $WT_RC -ne 0 ]; then
    exit 1
fi
