#!/bin/bash

# Comprehensive Deployment Script with Fixes
# Handles the complete deployment process with all discovered fixes

set -e

COMPOSE_FILE="infra/compose/docker-compose.local.yml"

echo "🚀 Starting comprehensive deployment with fixes..."

# Step 1: Create networks
echo "🌐 Creating Docker networks..."
./scripts/create-networks.sh

# Step 2: Generate certificates
echo "🔐 Generating development certificates..."
./scripts/generate-dev-certs.sh

# Step 3: Start core infrastructure first
echo "🏗️  Starting core infrastructure..."
cd infra/compose
docker compose -f docker-compose.local.yml up -d ata-traefik ata-postgres ata-redis
cd ../..

# Step 4: Wait for core services and fix database issues
echo "⏳ Waiting for core services..."
sleep 15
./scripts/fix-database-issues.sh

# Step 5: Start Authentik components in order
echo "🔐 Starting Authentik components..."
cd infra/compose
docker compose -f docker-compose.local.yml up -d ata-authentik-db ata-authentik-redis
sleep 10
docker compose -f docker-compose.local.yml up -d ata-authentik-server
sleep 15
docker compose -f docker-compose.local.yml up -d ata-authentik-worker ata-authentik-outpost
cd ../..

# Step 6: Start remaining infrastructure
echo "🏗️  Starting remaining infrastructure..."
cd infra/compose
docker compose -f docker-compose.local.yml up -d ata-vault ata-neo4j ata-qdrant ata-minio ata-prometheus ata-grafana ata-loki
cd ../..

# Step 7: Wait and verify Authentik is healthy
echo "⏳ Waiting for Authentik to be healthy..."
timeout=120
counter=0
while [ "$(docker inspect --format='{{.State.Health.Status}}' ata-authentik-server 2>/dev/null)" != "healthy" ]; do
    if [ $counter -ge $timeout ]; then
        echo "❌ Authentik server failed to become healthy within $timeout seconds"
        echo "📋 Checking logs..."
        docker compose -f infra/compose/docker-compose.local.yml logs --tail=10 ata-authentik-server
        exit 1
    fi
    sleep 2
    counter=$((counter + 2))
    echo "⏳ Waiting for Authentik... ($counter/$timeout seconds)"
done
echo "✅ Authentik is healthy"

# Step 8: Start application services
echo "🚀 Starting application services..."
cd infra/compose
docker compose -f docker-compose.local.yml up -d \
    ata-svc-ingestion ata-svc-extract ata-svc-forms ata-svc-hmrc ata-svc-kg \
    ata-svc-normalize-map ata-svc-ocr ata-svc-rag-indexer ata-svc-rag-retriever \
    ata-svc-reason ata-svc-rpa ata-svc-firm-connectors ata-svc-coverage ata-ui-review
cd ../..

# Step 9: Start Unleash (may fail, but that's OK)
echo "📊 Starting Unleash (may require manual configuration)..."
cd infra/compose
docker compose -f docker-compose.local.yml up -d ata-unleash || echo "⚠️  Unleash failed to start - may need manual token configuration"
cd ../..

# Step 10: Final verification
echo "🔍 Running final verification..."
sleep 10
./scripts/verify-infra.sh || echo "⚠️  Some services may need additional configuration"

echo ""
echo "🎉 Deployment complete!"
echo ""
echo "📋 Next steps:"
echo "  1. Complete Authentik setup: https://auth.local/if/flow/initial-setup/"
echo "  2. Configure applications in Authentik admin panel"
echo "  3. Test protected services redirect to Authentik"
echo ""
echo "🌐 Available endpoints:"
echo "  • Traefik Dashboard: http://localhost:8080"
echo "  • Authentik: https://auth.local"
echo "  • Grafana: https://grafana.local"
echo "  • Review UI: https://review.local (requires Authentik setup)"
echo ""
echo "🔧 Troubleshooting:"
echo "  • Check logs: make logs"
echo "  • Check status: make status"
echo "  • Restart services: make restart"
