# Script de Build Android APK Release - UnionFlow Mobile
# Usage: .\build-android-release.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 APK Release Build          ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝

"@ -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"

# 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 APK
Write-Info "Build APK Release en cours..."
Write-Info "Ceci peut prendre quelques minutes..."

$buildArgs = @(
    "build",
    "apk",
    "--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 APK échoué"
    exit 1
}

# Résultat
$apkPath = "build\app\outputs\flutter-apk\app-release.apk"
$apkFullPath = Join-Path $projectRoot $apkPath

if (Test-Path $apkFullPath) {
    $apkSize = (Get-Item $apkFullPath).Length / 1MB
    $apkSizeFormatted = "{0:N2} MB" -f $apkSize

    Write-Host ""
    Write-Success "Build APK terminé avec succès!"
    Write-Host ""
    Write-Host "┌─────────────────────────────────────────────────────────┐" -ForegroundColor Green
    Write-Host "│  Fichier: $apkPath" -ForegroundColor Green
    Write-Host "│  Taille: $apkSizeFormatted" -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"
    $outputApk = Join-Path $outputDir "unionflow-$env-$timestamp.apk"
    Copy-Item $apkFullPath $outputApk
    Write-Success "APK copié vers: outputs\unionflow-$env-$timestamp.apk"

    Write-Host ""
    Write-Info "Pour installer sur un device Android:"
    Write-Host "  adb install $apkPath" -ForegroundColor Yellow
    Write-Host ""
} else {
    Write-Error "APK non trouvé à l'emplacement attendu"
    exit 1
}
