# ============================================================================
# EasyStream - Quick Deploy Script
# ============================================================================
# This script automates the deployment process
#
# Usage:
#   .\deploy.ps1 -Mode dev         # Development deployment
#   .\deploy.ps1 -Mode prod        # Production deployment
#   .\deploy.ps1 -Mode test        # Test configuration only
# ============================================================================

param(
    [Parameter(Mandatory=$true)]
    [ValidateSet("dev", "prod", "test")]
    [string]$Mode,

    [switch]$SkipSync = $false,
    [switch]$SkipBuild = $false,
    [switch]$Verbose = $false
)

$ErrorActionPreference = "Stop"

Write-Host ""
Write-Host "============================================================================" -ForegroundColor Cyan
Write-Host "  EasyStream Deployment Script" -ForegroundColor Cyan
Write-Host "  Mode: $Mode" -ForegroundColor Yellow
Write-Host "============================================================================" -ForegroundColor Cyan
Write-Host ""

# ============================================================================
# Functions
# ============================================================================

function Test-Prerequisites {
    Write-Host "[1/9] Checking prerequisites..." -ForegroundColor Cyan

    # Check Docker
    try {
        $dockerVersion = docker --version
        Write-Host "  ✓ Docker: $dockerVersion" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Docker not found! Please install Docker Desktop." -ForegroundColor Red
        exit 1
    }

    # Check Docker Compose
    try {
        $composeVersion = docker-compose --version
        Write-Host "  ✓ Docker Compose: $composeVersion" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Docker Compose not found!" -ForegroundColor Red
        exit 1
    }

    # Check if Docker is running
    try {
        docker ps | Out-Null
        Write-Host "  ✓ Docker daemon is running" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Docker daemon is not running! Please start Docker Desktop." -ForegroundColor Red
        exit 1
    }

    Write-Host ""
}

function Test-Configuration {
    Write-Host "[2/9] Validating configuration..." -ForegroundColor Cyan

    # Check required files
    $requiredFiles = @(
        "docker-compose.yml",
        ".env",
        "__install\easystream.sql",
        "__install\add_advanced_features.sql",
        "deploy\init_settings.sql",
        "Dockerfile.php",
        "Dockerfile.cron",
        "Caddyfile"
    )

    $missing = @()
    foreach ($file in $requiredFiles) {
        if (Test-Path $file) {
            Write-Host "  ✓ $file" -ForegroundColor Green
        } else {
            Write-Host "  ✗ $file (MISSING)" -ForegroundColor Red
            $missing += $file
        }
    }

    if ($missing.Count -gt 0) {
        Write-Host ""
        Write-Host "ERROR: Missing required files!" -ForegroundColor Red
        exit 1
    }

    Write-Host ""
}

function Sync-ToDockerProgs {
    if ($SkipSync) {
        Write-Host "[3/9] Skipping folder sync (--SkipSync)" -ForegroundColor Yellow
        Write-Host ""
        return
    }

    Write-Host "[3/9] Syncing to docker-progs..." -ForegroundColor Cyan

    if (Test-Path "sync-to-docker-progs.ps1") {
        try {
            & .\sync-to-docker-progs.ps1
            Write-Host "  ✓ Sync completed" -ForegroundColor Green
        } catch {
            Write-Host "  ✗ Sync failed: $($_.Exception.Message)" -ForegroundColor Red
            Write-Host "  Continuing anyway..." -ForegroundColor Yellow
        }
    } else {
        Write-Host "  ! Sync script not found, skipping" -ForegroundColor Yellow
    }

    Write-Host ""
}

function Stop-ExistingServices {
    Write-Host "[4/9] Stopping existing services..." -ForegroundColor Cyan

    try {
        if ($Mode -eq "prod") {
            docker-compose -f docker-compose.prod.yml down 2>$null
        } else {
            docker-compose down 2>$null
        }
        Write-Host "  ✓ Services stopped" -ForegroundColor Green
    } catch {
        Write-Host "  ! No services were running" -ForegroundColor Yellow
    }

    Write-Host ""
}

function Build-Images {
    if ($SkipBuild) {
        Write-Host "[5/9] Skipping image build (--SkipBuild)" -ForegroundColor Yellow
        Write-Host ""
        return
    }

    Write-Host "[5/9] Building Docker images..." -ForegroundColor Cyan

    try {
        if ($Mode -eq "prod") {
            docker-compose -f docker-compose.prod.yml build
        } else {
            docker-compose build
        }
        Write-Host "  ✓ Images built successfully" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Build failed: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }

    Write-Host ""
}

function Start-Services {
    Write-Host "[6/9] Starting services..." -ForegroundColor Cyan

    try {
        if ($Mode -eq "prod") {
            docker-compose -f docker-compose.prod.yml up -d
        } else {
            docker-compose up -d
        }
        Write-Host "  ✓ Services started" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Failed to start services: $($_.Exception.Message)" -ForegroundColor Red
        exit 1
    }

    Write-Host ""
}

function Wait-ForServices {
    Write-Host "[7/9] Waiting for services to be ready..." -ForegroundColor Cyan
    Write-Host "  This may take 2-3 minutes for database initialization..." -ForegroundColor Yellow

    Start-Sleep -Seconds 5

    $maxWait = 180
    $waited = 0
    $healthy = $false

    while ($waited -lt $maxWait) {
        try {
            if ($Mode -eq "prod") {
                $status = docker-compose -f docker-compose.prod.yml ps --format json | ConvertFrom-Json
            } else {
                $status = docker-compose ps --format json | ConvertFrom-Json
            }

            # Check if database is healthy
            $dbHealthy = $status | Where-Object { $_.Service -eq "db" -and $_.Health -eq "healthy" }

            if ($dbHealthy) {
                $healthy = $true
                break
            }

            Write-Host "  ⏳ Waiting... ($waited/$maxWait seconds)" -ForegroundColor Gray
            Start-Sleep -Seconds 10
            $waited += 10
        } catch {
            Start-Sleep -Seconds 10
            $waited += 10
        }
    }

    if ($healthy) {
        Write-Host "  ✓ Services are ready" -ForegroundColor Green
    } else {
        Write-Host "  ! Services may not be fully ready (timeout)" -ForegroundColor Yellow
        Write-Host "  Check logs: docker-compose logs -f" -ForegroundColor Yellow
    }

    Write-Host ""
}

function Test-Deployment {
    Write-Host "[8/9] Testing deployment..." -ForegroundColor Cyan

    # Test database connection
    try {
        if ($Mode -eq "prod") {
            docker-compose -f docker-compose.prod.yml exec -T php php -r "new PDO('mysql:host=db;dbname=easystream', 'easystream', getenv('DB_PASS') ?: 'easystream'); echo 'OK';" | Out-Null
        } else {
            docker-compose exec -T php php -r "new PDO('mysql:host=db;dbname=easystream', 'easystream', 'easystream'); echo 'OK';" | Out-Null
        }
        Write-Host "  ✓ Database connection successful" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Database connection failed" -ForegroundColor Red
    }

    # Test Redis connection
    try {
        if ($Mode -eq "prod") {
            docker-compose -f docker-compose.prod.yml exec -T redis redis-cli ping | Out-Null
        } else {
            docker-compose exec -T redis redis-cli ping | Out-Null
        }
        Write-Host "  ✓ Redis connection successful" -ForegroundColor Green
    } catch {
        Write-Host "  ✗ Redis connection failed" -ForegroundColor Red
    }

    Write-Host ""
}

function Show-DeploymentInfo {
    Write-Host "[9/9] Deployment complete!" -ForegroundColor Green
    Write-Host ""
    Write-Host "============================================================================" -ForegroundColor Cyan
    Write-Host "  EasyStream is now running!" -ForegroundColor Green
    Write-Host "============================================================================" -ForegroundColor Cyan
    Write-Host ""

    if ($Mode -eq "dev") {
        Write-Host "Access URLs:" -ForegroundColor Yellow
        Write-Host "  Frontend:    http://localhost:8083" -ForegroundColor White
        Write-Host "  Admin Panel: http://localhost:8083/admin" -ForegroundColor White
        Write-Host "  RTMP Stream: rtmp://localhost:1935/live/testkey" -ForegroundColor White
        Write-Host ""
        Write-Host "Default Admin Credentials:" -ForegroundColor Yellow
        Write-Host "  Username: admin" -ForegroundColor White
        Write-Host "  Password: admin123" -ForegroundColor White
        Write-Host "  ⚠️  CHANGE THIS IMMEDIATELY!" -ForegroundColor Red
    } else {
        Write-Host "Production deployment complete!" -ForegroundColor Green
        Write-Host "  Check your MAIN_URL configuration for access" -ForegroundColor White
        Write-Host "  Ensure you've changed all default passwords!" -ForegroundColor Yellow
    }

    Write-Host ""
    Write-Host "Useful Commands:" -ForegroundColor Yellow
    if ($Mode -eq "prod") {
        Write-Host "  View logs:    docker-compose -f docker-compose.prod.yml logs -f" -ForegroundColor White
        Write-Host "  Check status: docker-compose -f docker-compose.prod.yml ps" -ForegroundColor White
        Write-Host "  Stop:         docker-compose -f docker-compose.prod.yml down" -ForegroundColor White
    } else {
        Write-Host "  View logs:    docker-compose logs -f" -ForegroundColor White
        Write-Host "  Check status: docker-compose ps" -ForegroundColor White
        Write-Host "  Stop:         docker-compose down" -ForegroundColor White
    }
    Write-Host ""
    Write-Host "============================================================================" -ForegroundColor Cyan
    Write-Host ""
}

# ============================================================================
# Main Execution
# ============================================================================

if ($Mode -eq "test") {
    Test-Prerequisites
    Test-Configuration
    Write-Host "Configuration test passed! Ready for deployment." -ForegroundColor Green
    exit 0
}

# Production warning
if ($Mode -eq "prod") {
    Write-Host "⚠️  PRODUCTION DEPLOYMENT" -ForegroundColor Red
    Write-Host "Make sure you have:" -ForegroundColor Yellow
    Write-Host "  1. Generated secure secrets (.\generate-secrets.ps1)" -ForegroundColor White
    Write-Host "  2. Updated .env.production" -ForegroundColor White
    Write-Host "  3. Configured SSL certificates" -ForegroundColor White
    Write-Host ""
    $confirm = Read-Host "Continue? (yes/no)"
    if ($confirm -ne "yes") {
        Write-Host "Deployment cancelled." -ForegroundColor Yellow
        exit 0
    }
    Write-Host ""
}

# Run deployment steps
Test-Prerequisites
Test-Configuration
Sync-ToDockerProgs
Stop-ExistingServices
Build-Images
Start-Services
Wait-ForServices
Test-Deployment
Show-DeploymentInfo
