#!/bin/bash

# Production Deployment Script
# Deploys the Torrent Gateway to production environment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
DEPLOY_ENV="${1:-production}"
VERSION="${2:-$(git rev-parse --short HEAD)}"

echo "🚀 Deploying Torrent Gateway"
echo "Environment: $DEPLOY_ENV"
echo "Version: $VERSION"
echo "Project root: $PROJECT_ROOT"
echo ""

cd "$PROJECT_ROOT"

# Pre-deployment checks
echo "📋 Running pre-deployment checks..."

# Check if git is clean
if [ "$DEPLOY_ENV" = "production" ] && [ -n "$(git status --porcelain)" ]; then
    echo "❌ Git working directory is not clean"
    echo "Please commit or stash changes before deploying to production"
    exit 1
fi

# Check if required files exist
REQUIRED_FILES=(
    "configs/config.yaml"
    "docker-compose.prod.yml"
    "configs/prometheus.yml"
    "configs/alertmanager.yml"
)

for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$file" ]; then
        echo "❌ Required file missing: $file"
        exit 1
    fi
done
echo "✅ Pre-deployment checks passed"

# Backup current deployment
echo "💾 Creating backup..."
./scripts/backup.sh
echo "✅ Backup completed"

# Build application
echo "🔨 Building application..."
go build -o bin/gateway \
    -ldflags "-X main.version=$VERSION -X main.buildTime=$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
    cmd/gateway/main.go

if [ ! -f "bin/gateway" ]; then
    echo "❌ Build failed"
    exit 1
fi
echo "✅ Application built successfully"

# Run tests
echo "🧪 Running tests..."
if ! go test ./test/... -timeout 5m; then
    echo "❌ Tests failed"
    echo "Deployment aborted"
    exit 1
fi
echo "✅ Tests passed"

# Build Docker images
echo "🐳 Building Docker images..."
docker build -f Dockerfile.prod -t torrent-gateway:$VERSION .
docker build -f Dockerfile.prod -t torrent-gateway:latest .
echo "✅ Docker images built"

# Stop existing services gracefully
echo "🛑 Stopping existing services..."
if docker-compose -f docker-compose.prod.yml ps | grep -q "Up"; then
    docker-compose -f docker-compose.prod.yml down --timeout 30
fi
echo "✅ Existing services stopped"

# Deploy new version
echo "🚀 Deploying new version..."
docker-compose -f docker-compose.prod.yml up -d

# Wait for services to be healthy
echo "⏳ Waiting for services to be healthy..."
TIMEOUT=60
COUNT=0

while [ $COUNT -lt $TIMEOUT ]; do
    if curl -sf http://localhost:9876/api/health > /dev/null; then
        echo "✅ Gateway is healthy"
        break
    fi
    
    COUNT=$((COUNT + 1))
    sleep 1
    echo "Waiting... ($COUNT/$TIMEOUT)"
done

if [ $COUNT -ge $TIMEOUT ]; then
    echo "❌ Gateway failed to become healthy within $TIMEOUT seconds"
    echo "Rolling back..."
    ./scripts/restore.sh
    exit 1
fi

# Run health checks
echo "🏥 Running post-deployment health checks..."
./scripts/health_check.sh

if [ $? -ne 0 ]; then
    echo "❌ Health checks failed"
    echo "Rolling back..."
    ./scripts/restore.sh
    exit 1
fi

# Tag successful deployment
echo "🏷️  Tagging deployment..."
git tag -a "deploy-$VERSION" -m "Deployment $VERSION to $DEPLOY_ENV"

echo ""
echo "🎉 Deployment completed successfully!"
echo "✅ Version $VERSION deployed to $DEPLOY_ENV"
echo "✅ All health checks passed"
echo "✅ Services are running and healthy"
echo ""
echo "📊 Access points:"
echo "   Gateway API: http://localhost:9876"
echo "   Admin Panel: http://localhost:9876/admin"
echo "   Grafana:     http://localhost:3000 (admin/admin123)"
echo "   Prometheus:  http://localhost:9090"
echo "   AlertManager: http://localhost:9093"
echo ""
echo "📝 Next steps:"
echo "   - Monitor logs: docker-compose -f docker-compose.prod.yml logs -f"
echo "   - Check metrics: curl http://localhost:9876/metrics"
echo "   - Run E2E tests: ./test/e2e/run_all_tests.sh"