#!/usr/bin/env bash

# Full Production Test Environment Script
set -e

echo "Starting Full Production Test Environment with Podman and SQLite..."

# Clean up any existing containers
echo "Cleaning up existing containers..."
docker-compose -f deployments/docker-compose.prod.yml down -v

# Create necessary directories
echo "Creating directories..."
mkdir -p data logs

# Build and start services
echo "Building and starting services..."
docker-compose -f deployments/docker-compose.prod.yml up --build -d

# Wait for services to be healthy
echo "Waiting for services to be healthy..."
sleep 15

# Check service health
echo "Checking service health..."
docker-compose -f deployments/docker-compose.prod.yml ps

# Test API server
echo "Testing API server..."
curl -k -s https://localhost:9103/health || echo "API health check failed"

# Test Redis
echo "Testing Redis..."
docker exec ml-prod-redis redis-cli ping || echo "Redis health check failed"

# Test SSH connectivity between containers
echo "Testing SSH connectivity..."
docker exec ml-prod-worker ssh -o StrictHostKeyChecking=no -o Port=2222 -i /home/worker/.ssh/id_rsa worker@localhost "echo 'SSH OK'" || echo "SSH test failed"

echo ""
echo "Full production test environment is ready!"
echo ""
echo "Services:"
echo "  - API Server: https://localhost:9103"
echo "  - SSH: localhost:2222 (worker user)"
echo "  - Redis: localhost:6379"
echo "  - Metrics: http://localhost:9100"
echo ""
echo "Features enabled:"
echo "  Auth with homelab_user/password"
echo "  SQLite database at /app/data/fetch_ml.db"
echo "  Podman containerized job execution"
echo "  SSH communication between containers"
echo "  TLS encryption"
echo "  Rate limiting and security"
echo ""
echo "To test with CLI:"
echo "  ./cli/zig-out/bin/ml queue prod-test-job"
echo "  ./cli/zig-out/bin/ml status"
echo ""
echo "To view logs:"
echo "  docker-compose -f deployments/docker-compose.prod.yml logs -f worker"
echo "  docker-compose -f deployments/docker-compose.prod.yml down"
echo ""
echo "To stop:"
echo "  docker-compose -f deployments/docker-compose.prod.yml down"
