#!/bin/bash
# Quick-start script for running E2E tests in GCP Workbench
# Usage: ./run_e2e_tests.sh [options]

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Configuration
PROJECT_ROOT="/home/coder/emms/sdk.worktrees/development/mca-prototype"
WAIT_TIME=15
TIMEOUT=300

# Parse arguments
TEST_SUITE="all"
VERBOSE=""
PARALLEL=""

while [[ $# -gt 0 ]]; do
    case $1 in
        -m|--metrics)
            TEST_SUITE="metrics"
            shift
            ;;
        -l|--logs)
            TEST_SUITE="logs"
            shift
            ;;
        -t|--traces)
            TEST_SUITE="traces"
            shift
            ;;
        -e|--errors)
            TEST_SUITE="errors"
            shift
            ;;
        -M|--multi-model)
            TEST_SUITE="multi-model"
            shift
            ;;
        -v|--verbose)
            VERBOSE="-s"
            shift
            ;;
        -p|--parallel)
            PARALLEL="-n 4"
            shift
            ;;
        -h|--help)
            echo "Usage: $0 [options]"
            echo ""
            echo "Options:"
            echo "  -m, --metrics      Run only metrics tests"
            echo "  -l, --logs         Run only logs tests"
            echo "  -t, --traces       Run only traces tests"
            echo "  -e, --errors       Run only error scenario tests"
            echo "  -M, --multi-model  Run only multi-model tests"
            echo "  -v, --verbose      Verbose output with print statements"
            echo "  -p, --parallel     Run tests in parallel (requires pytest-xdist)"
            echo "  -h, --help         Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                 # Run all tests"
            echo "  $0 -m -v          # Run metrics tests with verbose output"
            echo "  $0 -p             # Run all tests in parallel"
            exit 0
            ;;
        *)
            echo -e "${RED}Unknown option: $1${NC}"
            echo "Use -h or --help for usage information"
            exit 1
            ;;
    esac
done

echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}  MCA SDK E2E Test Runner${NC}"
echo -e "${BLUE}======================================${NC}"
echo ""

# Change to project directory
cd "$PROJECT_ROOT" || {
    echo -e "${RED}❌ Error: Cannot find project directory: $PROJECT_ROOT${NC}"
    exit 1
}

echo -e "${GREEN}📁 Project directory: $PROJECT_ROOT${NC}"
echo ""

# Check prerequisites
echo -e "${YELLOW}🔍 Checking prerequisites...${NC}"

# Check Docker
if ! command -v docker &> /dev/null; then
    echo -e "${RED}❌ Docker not found. Please install Docker.${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Docker: $(docker --version)${NC}"

# Check Docker Compose
if docker compose version &> /dev/null; then
    DOCKER_COMPOSE_CMD="docker compose"
    echo -e "${GREEN}✅ Docker Compose: $(docker compose version)${NC}"
elif command -v docker-compose &> /dev/null; then
    DOCKER_COMPOSE_CMD="docker-compose"
    echo -e "${GREEN}✅ Docker Compose: $(docker-compose --version)${NC}"
else
    echo -e "${RED}❌ Docker Compose not found${NC}"
    exit 1
fi

# Check pytest
if ! python3 -m pytest --version &> /dev/null; then
    echo -e "${RED}❌ Pytest not found. Installing...${NC}"
    pip install pytest pytest-timeout
fi
echo -e "${GREEN}✅ Pytest: $(python3 -m pytest --version 2>&1 | head -1)${NC}"

echo ""

# Create test-exports directory
echo -e "${YELLOW}📂 Preparing test environment...${NC}"
mkdir -p test-exports
chmod 777 test-exports
rm -f test-exports/*.json
echo -e "${GREEN}✅ Test exports directory ready${NC}"

# Stop any existing collector
echo -e "${YELLOW}🛑 Stopping any existing collector...${NC}"
$DOCKER_COMPOSE_CMD down 2>/dev/null || true

# Start OTel Collector
echo -e "${YELLOW}🚀 Starting OTel Collector...${NC}"
$DOCKER_COMPOSE_CMD up -d otel-collector

if [ $? -ne 0 ]; then
    echo -e "${RED}❌ Failed to start OTel Collector${NC}"
    echo -e "${YELLOW}Check logs: $DOCKER_COMPOSE_CMD logs otel-collector${NC}"
    exit 1
fi

echo -e "${GREEN}✅ OTel Collector started${NC}"
echo ""

# Wait for collector to be healthy
echo -e "${YELLOW}⏳ Waiting ${WAIT_TIME}s for collector to be healthy...${NC}"
sleep 5

# Check collector health
MAX_RETRIES=10
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
    if curl -s http://localhost:13133/ > /dev/null; then
        echo -e "${GREEN}✅ OTel Collector is healthy${NC}"
        break
    fi
    RETRY_COUNT=$((RETRY_COUNT + 1))
    echo -e "${YELLOW}   Retry $RETRY_COUNT/$MAX_RETRIES...${NC}"
    sleep 2
done

if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
    echo -e "${RED}❌ OTel Collector failed to become healthy${NC}"
    echo -e "${YELLOW}Showing collector logs:${NC}"
    $DOCKER_COMPOSE_CMD logs otel-collector | tail -30
    $DOCKER_COMPOSE_CMD down
    exit 1
fi

echo ""

# Determine test path
case $TEST_SUITE in
    metrics)
        TEST_PATH="tests/e2e/test_metrics_e2e.py"
        echo -e "${BLUE}🧪 Running Metrics E2E Tests (3 tests)${NC}"
        ;;
    logs)
        TEST_PATH="tests/e2e/test_logs_e2e.py"
        echo -e "${BLUE}🧪 Running Logs E2E Tests (3 tests)${NC}"
        ;;
    traces)
        TEST_PATH="tests/e2e/test_traces_e2e.py"
        echo -e "${BLUE}🧪 Running Traces E2E Tests (4 tests)${NC}"
        ;;
    errors)
        TEST_PATH="tests/e2e/test_error_scenarios_e2e.py"
        echo -e "${BLUE}🧪 Running Error Scenarios E2E Tests (5 tests)${NC}"
        ;;
    multi-model)
        TEST_PATH="tests/e2e/test_multi_model_e2e.py"
        echo -e "${BLUE}🧪 Running Multi-Model E2E Tests (4 tests)${NC}"
        ;;
    all)
        TEST_PATH="tests/e2e/"
        echo -e "${BLUE}🧪 Running All E2E Tests (19 tests)${NC}"
        ;;
esac

echo ""

# Run tests
TEST_CMD="python3 -m pytest $TEST_PATH -v $VERBOSE $PARALLEL --timeout=$TIMEOUT"
echo -e "${YELLOW}Running: $TEST_CMD${NC}"
echo ""

# Execute tests
if $TEST_CMD; then
    echo ""
    echo -e "${GREEN}======================================${NC}"
    echo -e "${GREEN}  ✅ All Tests Passed!${NC}"
    echo -e "${GREEN}======================================${NC}"
    TEST_RESULT=0
else
    echo ""
    echo -e "${RED}======================================${NC}"
    echo -e "${RED}  ❌ Some Tests Failed${NC}"
    echo -e "${RED}======================================${NC}"
    TEST_RESULT=1
fi

echo ""

# Show export files
echo -e "${YELLOW}📊 Generated export files:${NC}"
if [ -d "test-exports" ] && [ "$(ls -A test-exports/*.json 2>/dev/null)" ]; then
    ls -lh test-exports/*.json
    echo ""
    echo -e "${YELLOW}Preview first metric:${NC}"
    cat test-exports/otel-metrics.json 2>/dev/null | head -1 | python3 -m json.tool 2>/dev/null || echo "No metrics found"
else
    echo -e "${YELLOW}No export files generated (tests may not have run successfully)${NC}"
fi

echo ""

# Cleanup
echo -e "${YELLOW}🧹 Cleaning up...${NC}"
$DOCKER_COMPOSE_CMD down

if [ $TEST_RESULT -eq 0 ]; then
    echo -e "${GREEN}✅ Cleanup complete${NC}"
else
    echo -e "${YELLOW}⚠️  Cleanup complete (tests had failures)${NC}"
fi

echo ""
echo -e "${BLUE}======================================${NC}"
echo -e "${BLUE}  Test Run Complete${NC}"
echo -e "${BLUE}======================================${NC}"

exit $TEST_RESULT
