# Script de Build Android AAB (App Bundle) Release - UnionFlow Mobile
# Usage: .\build-android-bundle.ps1 [-env <dev|staging|prod>] [-clean]

param(
    [Parameter(Mandatory=$false)]
    [ValidateSet("dev", "staging", "prod")]
    [string]$env = "prod",

    [Parameter(Mandatory=$false)]
    [switch]$clean = $false
)

# Configuration
$ErrorActionPreference = "Stop"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$projectRoot = Join-Path $scriptDir "../.."

# Couleurs pour output
function Write-Success { param($msg) Write-Host "✅ $msg" -ForegroundColor Green }
function Write-Info { param($msg) Write-Host "ℹ️  $msg" -ForegroundColor Cyan }
function Write-Warning { param($msg) Write-Host "⚠️  $msg" -ForegroundColor Yellow }
function Write-Error { param($msg) Write-Host "❌ $msg" -ForegroundColor Red }

# Banner
Write-Host @"

╔══════════════════════════════════════════════════════════════╗
║                                                              ║
║      UnionFlow Mobile - Android AAB Release Build           ║
║              (Google Play Store Bundle)                     ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan

# Vérifier Flutter
Write-Info "Vérification de Flutter..."
try {
    $flutterVersion = flutter --version | Select-String -Pattern "Flutter (\d+\.\d+\.\d+)" | ForEach-Object { $_.Matches.Groups[1].Value }
    Write-Success "Flutter $flutterVersion détecté"
} catch {
    Write-Error "Flutter n'est pas installé ou n'est pas dans le PATH"
    exit 1
}

# Changement de répertoire
Set-Location $projectRoot
Write-Info "Répertoire de travail: $projectRoot"

# Vérification Keystore Production (AAB nécessite signing)
if ($env -eq "prod") {
    $keyPropertiesPath = Join-Path $projectRoot "android\key.properties"
    if (-not (Test-Path $keyPropertiesPath)) {
        Write-Warning "⚠️  Keystore de production non configuré!"
        Write-Warning "Le AAB sera signé avec le keystore debug (NON VALABLE POUR GOOGLE PLAY)"
        Write-Warning ""
        Write-Warning "Pour configurer le keystore de production:"
        Write-Warning "1. Générer keystore: keytool -genkey -v -keystore unionflow-release.keystore -alias unionflow -keyalg RSA -keysize 2048 -validity 10000"
        Write-Warning "2. Créer android\key.properties avec:"
        Write-Warning "   storePassword=<password>"
        Write-Warning "   keyPassword=<password>"
        Write-Warning "   keyAlias=unionflow"
        Write-Warning "   storeFile=../unionflow-release.keystore"
        Write-Warning ""
        $continue = Read-Host "Continuer avec keystore debug? (y/n)"
        if ($continue -ne "y") {
            Write-Error "Build annulé"
            exit 1
        }
    } else {
        Write-Success "Keystore de production détecté"
    }
}

# Configuration environnement
$apiUrl = ""
$keycloakUrl = ""
$wsUrl = ""

switch ($env) {
    "dev" {
        $apiUrl = "http://localhost:8085"
        $keycloakUrl = "http://localhost:8180"
        $wsUrl = "ws://localhost:8085"
    }
    "staging" {
        $apiUrl = "https://api-staging.lions.dev"
        $keycloakUrl = "https://security-staging.lions.dev"
        $wsUrl = "wss://api-staging.lions.dev"
    }
    "prod" {
        $apiUrl = "https://api.lions.dev"
        $keycloakUrl = "https://security.lions.dev"
        $wsUrl = "wss://api.lions.dev"
    }
}

Write-Info "Environnement: $env"
Write-Info "API URL: $apiUrl"
Write-Info "Keycloak URL: $keycloakUrl"
Write-Info "WebSocket URL: $wsUrl"

# Clean (optionnel)
if ($clean) {
    Write-Info "Nettoyage du build précédent..."
    flutter clean
    Write-Success "Nettoyage terminé"
}

# Get dependencies
Write-Info "Installation des dépendances..."
flutter pub get
Write-Success "Dépendances installées"

# Build runner
Write-Info "Génération du code (build_runner)..."
flutter pub run build_runner build --delete-conflicting-outputs
Write-Success "Code généré"

# Linting
Write-Info "Analyse du code..."
$analyzeResult = flutter analyze 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Warning "Analyse du code a détecté des problèmes:"
    Write-Host $analyzeResult
    $continue = Read-Host "Continuer quand même? (y/n)"
    if ($continue -ne "y") {
        Write-Error "Build annulé"
        exit 1
    }
}
Write-Success "Analyse terminée"

# Build AAB
Write-Info "Build App Bundle (AAB) Release en cours..."
Write-Info "Ceci peut prendre quelques minutes..."

$buildArgs = @(
    "build",
    "appbundle",
    "--release",
    "--dart-define=ENV=$env",
    "--dart-define=API_URL=$apiUrl",
    "--dart-define=KEYCLOAK_URL=$keycloakUrl",
    "--dart-define=WS_URL=$wsUrl"
)

# Obfuscation pour production
if ($env -eq "prod") {
    Write-Info "Activation de l'obfuscation..."
    $buildArgs += "--obfuscate"
    $buildArgs += "--split-debug-info=build/app/outputs/symbols"
}

& flutter $buildArgs

if ($LASTEXITCODE -ne 0) {
    Write-Error "Build AAB échoué"
    exit 1
}

# Résultat
$aabPath = "build\app\outputs\bundle\release\app-release.aab"
$aabFullPath = Join-Path $projectRoot $aabPath

if (Test-Path $aabFullPath) {
    $aabSize = (Get-Item $aabFullPath).Length / 1MB
    $aabSizeFormatted = "{0:N2} MB" -f $aabSize

    Write-Host ""
    Write-Success "Build AAB terminé avec succès!"
    Write-Host ""
    Write-Host "┌─────────────────────────────────────────────────────────┐" -ForegroundColor Green
    Write-Host "│  Fichier: $aabPath" -ForegroundColor Green
    Write-Host "│  Taille: $aabSizeFormatted" -ForegroundColor Green
    Write-Host "│  Environnement: $env" -ForegroundColor Green
    Write-Host "└─────────────────────────────────────────────────────────┘" -ForegroundColor Green
    Write-Host ""

    # Copie dans outputs/
    $outputDir = Join-Path $projectRoot "outputs"
    if (-not (Test-Path $outputDir)) {
        New-Item -ItemType Directory -Path $outputDir | Out-Null
    }

    $timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
    $outputAab = Join-Path $outputDir "unionflow-$env-$timestamp.aab"
    Copy-Item $aabFullPath $outputAab
    Write-Success "AAB copié vers: outputs\unionflow-$env-$timestamp.aab"

    # Symboles de debug
    $symbolsPath = Join-Path $projectRoot "build\app\outputs\symbols"
    if (Test-Path $symbolsPath) {
        $outputSymbols = Join-Path $outputDir "unionflow-$env-$timestamp-symbols.zip"
        Compress-Archive -Path $symbolsPath -DestinationPath $outputSymbols -Force
        Write-Success "Symboles de debug: outputs\unionflow-$env-$timestamp-symbols.zip"
    }

    Write-Host ""
    Write-Info "Prochaines étapes pour Google Play:"
    Write-Host "1. Se connecter à Google Play Console" -ForegroundColor Yellow
    Write-Host "2. Créer/Ouvrir l'application UnionFlow" -ForegroundColor Yellow
    Write-Host "3. Production → Create new release" -ForegroundColor Yellow
    Write-Host "4. Upload le AAB: $aabPath" -ForegroundColor Yellow
    if (Test-Path $symbolsPath) {
        Write-Host "5. Upload symboles de debug pour crash reporting" -ForegroundColor Yellow
    }
    Write-Host "6. Remplir les notes de version" -ForegroundColor Yellow
    Write-Host "7. Save → Review → Start rollout to production" -ForegroundColor Yellow
    Write-Host ""
} else {
    Write-Error "AAB non trouvé à l'emplacement attendu"
    exit 1
}
