#!/usr/bin/env bash
#
# Test Environment Setup Script
# Creates isolated test environment, runs smoke tests, verifies full stack
#

set -euo pipefail

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $*"
}

warn() {
    echo -e "${YELLOW}[$(date +'%Y-%m-%d %H:%M:%S')] WARNING:${NC} $*"
}

error() {
    echo -e "${RED}[$(date +'%Y-%m-%d %H:%M:%S')] ERROR:${NC} $*" >&2
}

log "Starting test environment setup..."

# Clean up any existing test environment
log "Cleaning up existing test environment..."
docker compose -f docker-compose.test.yml down -v 2>/dev/null || true
rm -rf /tmp/llmhost-test-data
mkdir -p /tmp/llmhost-test-data

# Start test environment
log "Starting test environment..."
docker compose -f docker-compose.test.yml --env-file .env.test up -d

# Wait for services to be healthy
log "Waiting for services to be healthy..."
sleep 10

# Check service health
log "Checking service health..."

# Check API
if curl -f -s http://localhost:4001/health > /dev/null; then
    log "✓ API health check passed (port 4001)"
else
    error "✗ API health check failed"
    docker compose -f docker-compose.test.yml logs llmhost-test
    exit 1
fi

# Check Frontend
if curl -f -s http://localhost:8001/api/health > /dev/null; then
    log "✓ Frontend health check passed (port 8001)"
else
    error "✗ Frontend health check failed"
    docker compose -f docker-compose.test.yml logs llmhost-frontend-test
    exit 1
fi

# Check Prometheus
if curl -f -s http://localhost:9092/-/healthy > /dev/null; then
    log "✓ Prometheus health check passed (port 9092)"
else
    warn "Prometheus health check failed (non-critical)"
fi

# Check Grafana
if curl -f -s http://localhost:3005/api/health > /dev/null; then
    log "✓ Grafana health check passed (port 3005)"
else
    warn "Grafana health check failed (non-critical)"
fi

# Run database migrations
log "Running database migrations..."
docker compose -f docker-compose.test.yml exec -T llmhost-test python -c "
from llmhost.database import init_db
import asyncio
asyncio.run(init_db())
print('Database initialized')
" || warn "Database migration warning (may already be initialized)"

# Smoke test: Create test user
log "Running smoke test: Create test user..."
REGISTER_RESPONSE=$(curl -s -X POST http://localhost:3001/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test@example.com",
    "password": "TestPassword123!",
    "name": "Test User"
  }')

if echo "$REGISTER_RESPONSE" | grep -q "error"; then
    warn "User registration response: $REGISTER_RESPONSE (may already exist)"
else
    log "✓ User registration smoke test passed"
fi

# Smoke test: Check metrics endpoint
log "Running smoke test: Metrics endpoint..."
METRICS=$(curl -s http://localhost:4001/metrics)
if echo "$METRICS" | grep -q "http_requests_total"; then
    log "✓ Metrics endpoint smoke test passed"
else
    error "✗ Metrics endpoint missing expected metrics"
    exit 1
fi

# Print service URLs
log ""
log "======================================"
log "Test Environment Ready!"
log "======================================"
log "API:        http://localhost:4001"
log "Frontend:   http://localhost:8001"
log "Prometheus: http://localhost:9092"
log "Grafana:    http://localhost:3005 (admin/test123)"
log "======================================"
log ""
log "To view logs:"
log "  docker compose -f docker-compose.test.yml logs -f"
log ""
log "To stop:"
log "  docker compose -f docker-compose.test.yml down"
log ""
log "To clean up:"
log "  docker compose -f docker-compose.test.yml down -v"
log "  rm -rf /tmp/llmhost-test-data"
log ""

exit 0
