# DevOps Windows Setup Script
# PowerShell 5.1+ requis

param(
    [switch]$SkipDocker = $false,
    [switch]$SkipK8s = $false,
    [switch]$Help = $false
)

if ($Help) {
    Write-Host "Usage: .\setup.ps1 [-SkipDocker] [-SkipK8s] [-Help]" -ForegroundColor Cyan
    Write-Host "  -SkipDocker   : Ne pas démarrer Docker Compose" -ForegroundColor Gray
    Write-Host "  -SkipK8s      : Ne pas déployer sur Kubernetes" -ForegroundColor Gray
    Write-Host "  -Help         : Afficher cette aide" -ForegroundColor Gray
    exit 0
}

Write-Host "========================================" -ForegroundColor Green
Write-Host "       DEVOPS WINDOWS SETUP" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""

# 1. VÃ©rification des outils
Write-Host "[1/5] Vérification des outils..." -ForegroundColor Yellow

$tools = @(
    @{Name="Docker"; Cmd="docker --version"},
    @{Name="kubectl"; Cmd="kubectl version --client"},
    @{Name="helm"; Cmd="helm version"},
    @{Name="python"; Cmd="python --version"}
)

foreach ($tool in $tools) {
    try {
        $output = Invoke-Expression $tool.Cmd 2>&1
        Write-Host "  ✅ $($tool.Name) : OK" -ForegroundColor Green
    } catch {
        Write-Host "  ❌ $($tool.Name) : MANQUANT" -ForegroundColor Red
        Write-Host "     Installez avec: choco install $($tool.Name.ToLower())" -ForegroundColor Gray
    }
}

Write-Host ""

# 2. Build de l'application
Write-Host "[2/5] Build de l'application Docker..." -ForegroundColor Yellow
try {
    Set-Location "$PSScriptRoot\..\src\app"
    docker build -t devops-app:local .
    Write-Host "  ✅ Image Docker construite" -ForegroundColor Green
    Set-Location $PSScriptRoot
} catch {
    Write-Host "  ❌ Erreur lors du build Docker" -ForegroundColor Red
    Write-Host $_.Exception.Message
    exit 1
}

# 3. Docker Compose
if (-not $SkipDocker) {
    Write-Host "[3/5] DÃ©marrage Docker Compose..." -ForegroundColor Yellow
    try {
        Set-Location "$PSScriptRoot\..\docker"
        
        # ArrÃªter si dÃ©jÃ  en cours
        docker-compose down 2>$null
        
        # DÃ©marrer
        docker-compose up -d
        
        # Attendre que les services soient prÃªts
        Start-Sleep -Seconds 10
        
        Write-Host "  ✅ Docker Compose dÃ©marrÃ©" -ForegroundColor Green
        Write-Host "     Attente supplÃ©mentaire pour les services..." -ForegroundColor Gray
        
        # VÃ©rifier l'application
        $attempts = 0
        $maxAttempts = 6
        while ($attempts -lt $maxAttempts) {
            try {
                $response = Invoke-WebRequest -Uri "http://localhost:8000/health" -UseBasicParsing -TimeoutSec 5
                if ($response.StatusCode -eq 200) {
                    Write-Host " ✅ Application accessible" -ForegroundColor Green
                    break
                }
            } catch {
                $attempts++
                Write-Host "  ⏳ Tentative $attempts/$maxAttempts..." -ForegroundColor Yellow
                Start-Sleep -Seconds 10
                
                if ($attempts -eq $maxAttempts) {
                    Write-Host "  ⚠️ Application lente Ã  dÃ©marrer" -ForegroundColor Yellow
                }
            }
        }
        
        Set-Location $PSScriptRoot
    } catch {
        Write-Host "  ⚠️  Erreur Docker Compose : $($_.Exception.Message)" -ForegroundColor Yellow
        Set-Location $PSScriptRoot
    }
}

# 4. Kubernetes
if (-not $SkipK8s) {
    Write-Host "[4/5] DÃ©ploiement Kubernetes..." -ForegroundColor Yellow
    try {
        Set-Location "$PSScriptRoot\..\kubernetes\manifests"
        
        # VÃ©rifier que Kubernetes est activÃ©
        $k8sContext = kubectl config current-context 2>$null
        if ($LASTEXITCODE -ne 0) {
            Write-Host " ℹ️ Kubernetes non configuré, passage au mode Docker uniquement" -ForegroundColor Yellow
        } else {
            # Appliquer les manifests
            kubectl apply -f namespace.yaml
            kubectl apply -f configmap.yaml
            kubectl apply -f deployment.yaml
            
            Write-Host " ✅ DÃ©ploiement Kubernetes terminÃ©" -ForegroundColor Green
            
            # Obtenir les infos
            $service = kubectl get svc -n devops-demo devops-app-service -o json | ConvertFrom-Json
            $nodePort = $service.spec.ports[0].nodePort
            Write-Host "     Accès K8s : http://localhost:$nodePort" -ForegroundColor Cyan
        }
        
        Set-Location $PSScriptRoot
    } catch {
        Write-Host "  ⚠️  Erreur Kubernetes : $($_.Exception.Message)" -ForegroundColor Yellow
        Set-Location $PSScriptRoot
    }
}

Write-Host "[5/5] RÃ©capitulatif..." -ForegroundColor Yellow
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "           SETUP TERMINÃ‰ !" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host ""
Write-Host "🌐 ACCèS AUX SERVICES :" -ForegroundColor White
Write-Host ""
Write-Host "  📊 Application FastAPI :" -ForegroundColor Cyan
Write-Host "     â€¢ Interface : http://localhost:8000" -ForegroundColor Gray
Write-Host "     â€¢ Health : http://localhost:8000/health" -ForegroundColor Gray
Write-Host "     â€¢ Docs : http://localhost:8000/docs" -ForegroundColor Gray
Write-Host "     â€¢ MÃ©triques : http://localhost:8000/metrics" -ForegroundColor Gray
Write-Host ""
Write-Host "  📈 Monitoring :" -ForegroundColor Cyan
Write-Host "     â€¢ Prometheus : http://localhost:9090" -ForegroundColor Gray
Write-Host "     â€¢ Grafana : http://localhost:3000" -ForegroundColor Gray
Write-Host "        Login : admin / admin123" -ForegroundColor DarkGray
Write-Host ""
Write-Host "  🐳 Gestion Docker :" -ForegroundColor Cyan
Write-Host "     â€¢ Portainer : http://localhost:9000" -ForegroundColor Gray
Write-Host ""
if (-not $SkipK8s) {
    Write-Host "  ☸️  Kubernetes :" -ForegroundColor Cyan
    Write-Host "     â€¢ VÃ©rifier : kubectl get pods -n devops-demo" -ForegroundColor Gray
    Write-Host "     â€¢ Logs : kubectl logs -f -n devops-demo -l app=devops-app" -ForegroundColor Gray
}
Write-Host ""
Write-Host "🔧 COMMANDES UTILES :" -ForegroundColor White
Write-Host "   * Voir les logs : docker-compose logs -f [app|prometheus|grafana]" -ForegroundColor DarkGray
Write-Host "   * ArrÃªter tout : docker-compose down" -ForegroundColor DarkGray
Write-Host "   * Nettoyer : docker system prune -a -f --volumes" -ForegroundColor DarkGray
Write-Host ""
Write-Host "💡 CONSEIL :" -ForegroundColor Yellow
Write-Host "   Testez avec : curl http://localhost:8000 ou dans PowerShell :" -ForegroundColor Gray
Write-Host "   Invoke-WebRequest -Uri 'http://localhost:8000' -UseBasicParsing" -ForegroundColor DarkGray
Write-Host ""

# Test automatique
try {
    $test = Invoke-WebRequest -Uri "http://localhost:8000/health" -UseBasicParsing -TimeoutSec 5
    if ($test.StatusCode -eq 200) {
        Write-Host "âœ… Test de santÃ© rÃ©ussi !" -ForegroundColor Green
    }
} catch {
    Write-Host "⚠️  L'application n'est pas encore accessible, patientez..." -ForegroundColor Yellow
}