#!/bin/bash

echo "🔧 Fixing Microservices Deployment Issues"
echo "========================================"

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 1. Stop all services
print_status "Stopping all services..."
docker-compose down --volumes --remove-orphans

# 2. Clean up Docker system
print_status "Cleaning up Docker system..."
docker system prune -f
docker volume prune -f

# 3. Remove problematic volumes
print_status "Removing problematic volumes..."
docker volume rm codenuk-backend-live_postgres_data 2>/dev/null || true
docker volume rm codenuk-backend-live_n8n_data 2>/dev/null || true
docker volume rm codenuk-backend-live_migration_state 2>/dev/null || true

# 4. Clean database schema conflicts
print_status "Preparing clean database environment..."
cat > /tmp/clean_db.sql << 'EOF'
-- Clean up any existing schema conflicts
DROP TYPE IF EXISTS claude_recommendations CASCADE;
DROP TABLE IF EXISTS claude_recommendations CASCADE;

-- Clean up n8n related tables if they exist
DROP TABLE IF EXISTS n8n_credentials_entity CASCADE;
DROP TABLE IF EXISTS n8n_execution_entity CASCADE;
DROP TABLE IF EXISTS n8n_workflow_entity CASCADE;
DROP TABLE IF EXISTS n8n_webhook_entity CASCADE;
DROP TABLE IF EXISTS n8n_tag_entity CASCADE;
DROP TABLE IF EXISTS n8n_workflows_tags CASCADE;

-- Reset any conflicting sequences
DROP SEQUENCE IF EXISTS claude_recommendations_id_seq CASCADE;
EOF

# 5. Start only core infrastructure first
print_status "Starting core infrastructure services..."
docker-compose up -d postgres redis mongodb rabbitmq

# 6. Wait for databases to be ready
print_status "Waiting for databases to be ready..."
sleep 30

# Check if postgres is ready
print_status "Checking PostgreSQL readiness..."
for i in {1..30}; do
    if docker exec pipeline_postgres pg_isready -U pipeline_admin -d dev_pipeline; then
        print_status "PostgreSQL is ready!"
        break
    fi
    print_warning "Waiting for PostgreSQL... ($i/30)"
    sleep 2
done

# 7. Clean the database
print_status "Cleaning database schema conflicts..."
docker exec -i pipeline_postgres psql -U pipeline_admin -d dev_pipeline < /tmp/clean_db.sql 2>/dev/null || true

# 8. Run migrations
print_status "Running database migrations..."
docker-compose up migrations

# Wait for migrations to complete
print_status "Waiting for migrations to complete..."
sleep 10

# 9. Start n8n with proper initialization
print_status "Starting n8n service..."
docker-compose up -d n8n

# Wait for n8n to initialize
print_status "Waiting for n8n to initialize..."
sleep 20

# 10. Start remaining services in batches
print_status "Starting core services..."
docker-compose up -d \
    api-gateway \
    requirement-processor \
    tech-stack-selector \
    architecture-designer

sleep 15

print_status "Starting generation services..."
docker-compose up -d \
    code-generator \
    test-generator \
    deployment-manager

sleep 15

print_status "Starting user services..."
docker-compose up -d \
    user-auth \
    template-manager \
    unison

sleep 15

print_status "Starting additional services..."
docker-compose up -d \
    ai-mockup-service \
    git-integration \
    self-improving-generator \
    web-dashboard

# 11. Final health check
print_status "Performing final health check..."
sleep 30

echo ""
echo "🏥 Service Health Check"
echo "======================"

# Check service status
docker-compose ps

echo ""
print_status "Deployment fix completed!"
print_warning "Please check the service status above."
print_warning "If any services are still failing, check their logs with:"
print_warning "docker-compose logs [service-name]"

# Clean up temp file
rm -f /tmp/clean_db.sql

echo ""
print_status "🎯 Next Steps:"
echo "1. Check service logs: docker-compose logs -f"
echo "2. Verify n8n is accessible: http://localhost:5678"
echo "3. Test API endpoints for health checks"
echo "4. Monitor for any remaining issues"
