#!/usr/bin/env pwsh
<#
.SYNOPSIS
    Script pour pousser Lions User Manager sur git.lions.dev

.DESCRIPTION
    Ce script crée les repositories et pousse les modules de lions-user-manager
    sur git.lions.dev pour permettre le déploiement avec lionsctl pipeline.

.PARAMETER Component
    Composant à pousser: 'api', 'server', 'client', ou 'all' (défaut: 'all')

.EXAMPLE
    .\push-to-git-lions.ps1 -Component all

.EXAMPLE
    .\push-to-git-lions.ps1 -Component client
#>

param(
    [Parameter(Mandatory=$false)]
    [ValidateSet('api', 'server', 'client', 'all')]
    [string]$Component = 'all'
)

# Configuration
$ErrorActionPreference = "Stop"
$GitServer = "https://git.lions.dev"
$GitOrg = "lionsdev"
$ApiRepo = "lions-user-manager-server-api"
$ServerRepo = "lions-user-manager-server-impl-quarkus"
$ClientRepo = "lions-user-manager-client-quarkus-primefaces-freya"

# Identifiants Git
$GitUsername = "lionsdev"
$GitPassword = "lions@2025"

# Chemins
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$ProjectRoot = Split-Path -Parent $ScriptDir
$ApiPath = Join-Path $ProjectRoot "lions-user-manager-server-api"
$ServerPath = Join-Path $ProjectRoot "lions-user-manager-server-impl-quarkus"
$ClientPath = Join-Path $ProjectRoot "lions-user-manager-client-quarkus-primefaces-freya"

# Couleurs
function Write-Success { Write-Host "✅ $args" -ForegroundColor Green }
function Write-Info { Write-Host "ℹ️  $args" -ForegroundColor Cyan }
function Write-Warning { Write-Host "⚠️  $args" -ForegroundColor Yellow }
function Write-Error { Write-Host "❌ $args" -ForegroundColor Red }
function Write-Step { Write-Host "`n🚀 $args" -ForegroundColor Magenta }

# Vérifier Git
function Test-Git {
    if (-not (Get-Command git -ErrorAction SilentlyContinue)) {
        Write-Error "Git n'est pas installé ou n'est pas dans le PATH"
        exit 1
    }
    Write-Success "Git trouvé: $(git --version)"
}

# Vérifier si un dépôt existe (via API Gitea)
function Test-GitRepository {
    param(
        [string]$RepoName
    )
    
    $repoUrl = "$GitServer/api/v1/repos/$GitOrg/$RepoName"
    $auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${GitUsername}:${GitPassword}"))
    
    $headers = @{
        "Authorization" = "Basic $auth"
    }
    
    try {
        $response = Invoke-RestMethod -Uri $repoUrl -Method Get -Headers $headers -ErrorAction SilentlyContinue
        Write-Success "Dépôt $RepoName existe déjà"
        return $true
    } catch {
        Write-Warning "Dépôt $RepoName n'existe pas. Veuillez le créer manuellement sur git.lions.dev"
        Write-Info "URL: $GitServer/$GitOrg/$RepoName"
        return $false
    }
}

# Pousser un module
function Push-Module {
    param(
        [string]$ModulePath,
        [string]$RepoName,
        [string]$Description,
        [string]$ComponentName
    )
    
    Write-Step "Push du $ComponentName vers git.lions.dev..."
    
    if (-not (Test-Path $ModulePath)) {
        Write-Error "Répertoire $ComponentName introuvable: $ModulePath"
        return $false
    }
    
    # Vérifier si le dépôt existe (optionnel, on essaie quand même de pousser)
    Write-Info "Vérification de l'existence du dépôt $RepoName..."
    $repoExists = Test-GitRepository -RepoName $RepoName
    if (-not $repoExists) {
        Write-Warning "Le dépôt $RepoName n'a pas été trouvé via l'API, mais on essaie quand même de pousser..."
        Write-Info "Si le push échoue, assurez-vous que le dépôt existe sur $GitServer/$GitOrg/$RepoName"
    }
    
    Push-Location $ModulePath
    try {
        # Vérifier si c'est un repo Git
        if (-not (Test-Path ".git")) {
            Write-Info "Initialisation du repository Git..."
            git init
            git add .
            git commit -m "Initial commit - $Description"
        } else {
            # Ajouter tous les fichiers modifiés
            git add .
            $hasChanges = git diff --cached --quiet
            if (-not $hasChanges) {
                git commit -m "Update - $Description" 2>$null
            }
        }
        
        # Vérifier la branche
        $currentBranch = git branch --show-current
        if ([string]::IsNullOrEmpty($currentBranch)) {
            Write-Info "Création de la branche main..."
            git checkout -b main 2>$null
        } elseif ($currentBranch -ne "main") {
            Write-Info "Renommage de la branche $currentBranch en main..."
            git branch -M main 2>$null
        }
        
        # Ajouter le remote git.lions.dev
        $remoteUrl = "$GitServer/$GitOrg/$RepoName.git"
        Write-Info "Ajout du remote: $remoteUrl"
        
        git remote remove lions 2>$null
        git remote add lions $remoteUrl
        
        # Encoder le mot de passe pour l'URL (le @ doit être %40)
        $encodedPassword = [System.Web.HttpUtility]::UrlEncode($GitPassword)
        $remoteUrlWithAuth = "$($GitServer.Replace('https://',"https://${GitUsername}:${encodedPassword}@"))/$GitOrg/$RepoName.git"
        git remote set-url lions $remoteUrlWithAuth
        
        # Pousser vers git.lions.dev
        Write-Info "Push vers git.lions.dev..."
        Write-Info "URL: $remoteUrl"
        
        $env:GIT_TERMINAL_PROMPT = "0"
        $env:GIT_ASKPASS = "echo"
        git push lions main --force 2>&1 | Out-String | Write-Host
        
        if ($LASTEXITCODE -eq 0) {
            Write-Success "$ComponentName poussé avec succès vers git.lions.dev"
            Write-Info "URL: $remoteUrl"
            return $true
        } else {
            Write-Error "Échec du push du $ComponentName"
            return $false
        }
        
    } finally {
        Pop-Location
    }
}

# Afficher les commandes de déploiement
function Show-DeploymentCommands {
    Write-Step "Commandes de déploiement avec lionsctl:"
    
    Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║                    📋 COMMANDES DE DÉPLOIEMENT                                ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan
    
    if ($Component -eq 'server' -or $Component -eq 'all') {
        Write-Host "🔨 SERVER (Backend Quarkus):" -ForegroundColor Yellow
        Write-Host ""
        Write-Host "# Développement (cluster k1)" -ForegroundColor Gray
        Write-Host "cd ../lions-infrastructure-2025/lionsctl" -ForegroundColor White
        Write-Host "./lionsctl.exe pipeline -u https://git.lions.dev/lionsdev/$ServerRepo -b main -j 17 -e dev -c k1 -m gbanedahoud@gmail.com" -ForegroundColor Green
        Write-Host ""
        Write-Host "# Production (cluster k2)" -ForegroundColor Gray
        Write-Host "cd ../lions-infrastructure-2025/lionsctl" -ForegroundColor White
        Write-Host "./lionsctl.exe pipeline -u https://git.lions.dev/lionsdev/$ServerRepo -b main -j 17 -e production -c k2 -m gbanedahoud@gmail.com" -ForegroundColor Green
        Write-Host ""
    }
    
    if ($Component -eq 'client' -or $Component -eq 'all') {
        Write-Host "🎨 CLIENT (Frontend Quarkus PrimeFaces):" -ForegroundColor Yellow
        Write-Host ""
        Write-Host "# Développement (cluster k1)" -ForegroundColor Gray
        Write-Host "cd ../lions-infrastructure-2025/lionsctl" -ForegroundColor White
        Write-Host "./lionsctl.exe pipeline -u https://git.lions.dev/lionsdev/$ClientRepo -b main -j 17 -e dev -c k1 -m gbanedahoud@gmail.com" -ForegroundColor Green
        Write-Host ""
        Write-Host "# Production (cluster k2)" -ForegroundColor Gray
        Write-Host "cd ../lions-infrastructure-2025/lionsctl" -ForegroundColor White
        Write-Host "./lionsctl.exe pipeline -u https://git.lions.dev/lionsdev/$ClientRepo -b main -j 17 -e production -c k2 -m gbanedahoud@gmail.com" -ForegroundColor Green
        Write-Host ""
    }
    
    Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║  💡 ASTUCE: Copiez-collez ces commandes pour déployer avec lionsctl !        ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan
}

# Main
function Main {
    Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║        🚀 PUSH LIONS USER MANAGER VERS GIT.LIONS.DEV 🚀                      ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan
    
    Write-Info "Composant: $Component"
    Write-Info "Serveur Git: $GitServer"
    Write-Info "Organisation: $GitOrg"
    Write-Info ""
    
    # Vérifier Git
    Test-Git
    
    # Push
    $success = $true
    
    if ($Component -eq 'api' -or $Component -eq 'all') {
        $result = Push-Module -ModulePath $ApiPath -RepoName $ApiRepo `
            -Description "Lions User Manager - Server API (DTOs, Interfaces)" `
            -ComponentName "API"
        $success = $success -and $result
    }
    
    if ($Component -eq 'server' -or $Component -eq 'all') {
        $result = Push-Module -ModulePath $ServerPath -RepoName $ServerRepo `
            -Description "Lions User Manager - Server Implementation (Quarkus)" `
            -ComponentName "Server"
        $success = $success -and $result
    }
    
    if ($Component -eq 'client' -or $Component -eq 'all') {
        $result = Push-Module -ModulePath $ClientPath -RepoName $ClientRepo `
            -Description "Lions User Manager - Client (Quarkus PrimeFaces Freya)" `
            -ComponentName "Client"
        $success = $success -and $result
    }
    
    if ($success) {
        # Afficher les commandes de déploiement
        Show-DeploymentCommands
        
        Write-Host @"

╔═══════════════════════════════════════════════════════════════════════════════╗
║                                                                               ║
║              ✅ PUSH TERMINÉ AVEC SUCCÈS ! ✅                                ║
║                                                                               ║
║  Vous pouvez maintenant déployer avec lionsctl pipeline (voir ci-dessus)   ║
║                                                                               ║
╚═══════════════════════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Green
    } else {
        Write-Error "Certains push ont échoué. Vérifiez les erreurs ci-dessus."
        exit 1
    }
}

# Exécuter
Main

