# Script de Build iOS IPA Release - UnionFlow Mobile
# Usage: .\build-ios-release.ps1 [-env <dev|staging|prod>] [-clean]
# NOTE: Nécessite macOS avec Xcode installé

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 - iOS IPA Release Build            ║
║                  (App Store Connect)                        ║
║                                                              ║
╚══════════════════════════════════════════════════════════════╝

"@ -ForegroundColor Cyan

# Vérifier OS
if (-not ($IsMacOS -or $IsOSX)) {
    Write-Error "Build iOS nécessite macOS avec Xcode installé"
    Write-Info "Utilisez un Mac ou un service de CI/CD cloud (Codemagic, Bitrise, etc.)"
    exit 1
}

# 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
}

# Vérifier Xcode
Write-Info "Vérification de Xcode..."
try {
    $xcodeVersion = xcodebuild -version | Select-String -Pattern "Xcode (\d+\.\d+)" | ForEach-Object { $_.Matches.Groups[1].Value }
    Write-Success "Xcode $xcodeVersion détecté"
} catch {
    Write-Error "Xcode n'est pas installé"
    Write-Info "Installer depuis App Store: https://apps.apple.com/us/app/xcode/id497799835"
    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"

# CocoaPods
Write-Info "Installation des CocoaPods..."
Set-Location "ios"
pod install
Set-Location ".."
Write-Success "CocoaPods installés"

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

# Avertissement pour production
if ($env -eq "prod") {
    Write-Warning "⚠️  Build iOS pour production"
    Write-Warning ""
    Write-Warning "Vérifier:"
    Write-Warning "1. Provisioning Profile configuré dans Xcode"
    Write-Warning "2. Signing Certificate valide"
    Write-Warning "3. App ID enregistré sur Apple Developer"
    Write-Warning "4. Version et Build Number mis à jour"
    Write-Warning ""
    $continue = Read-Host "Continuer? (y/n)"
    if ($continue -ne "y") {
        Write-Error "Build annulé"
        exit 1
    }
}

# Build IPA
Write-Info "Build IPA Release en cours..."
Write-Info "Ceci peut prendre plusieurs minutes..."

$buildArgs = @(
    "build",
    "ipa",
    "--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/ios/symbols"
}

& flutter $buildArgs

if ($LASTEXITCODE -ne 0) {
    Write-Error "Build IPA échoué"
    Write-Warning ""
    Write-Warning "Si erreur de signing, ouvrir Xcode:"
    Write-Warning "  open ios/Runner.xcworkspace"
    Write-Warning "Puis configurer Signing & Capabilities"
    exit 1
}

# Résultat
$ipaPath = "build/ios/ipa/unionflow_mobile_apps.ipa"
$ipaFullPath = Join-Path $projectRoot $ipaPath

if (Test-Path $ipaFullPath) {
    $ipaSize = (Get-Item $ipaFullPath).Length / 1MB
    $ipaSizeFormatted = "{0:N2} MB" -f $ipaSize

    Write-Host ""
    Write-Success "Build IPA terminé avec succès!"
    Write-Host ""
    Write-Host "┌─────────────────────────────────────────────────────────┐" -ForegroundColor Green
    Write-Host "│  Fichier: $ipaPath" -ForegroundColor Green
    Write-Host "│  Taille: $ipaSizeFormatted" -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"
    $outputIpa = Join-Path $outputDir "unionflow-$env-$timestamp.ipa"
    Copy-Item $ipaFullPath $outputIpa
    Write-Success "IPA copié vers: outputs/unionflow-$env-$timestamp.ipa"

    # Symboles de debug
    $symbolsPath = Join-Path $projectRoot "build/ios/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 App Store:"
    Write-Host "1. Ouvrir Xcode: open ios/Runner.xcworkspace" -ForegroundColor Yellow
    Write-Host "2. Product → Archive (Cmd+B puis Cmd+Shift+B)" -ForegroundColor Yellow
    Write-Host "3. Window → Organizer" -ForegroundColor Yellow
    Write-Host "4. Sélectionner l'archive → Distribute App" -ForegroundColor Yellow
    Write-Host "5. App Store Connect → Upload" -ForegroundColor Yellow
    Write-Host "6. Se connecter avec Apple ID Developer" -ForegroundColor Yellow
    Write-Host "7. Aller sur App Store Connect → My Apps → UnionFlow" -ForegroundColor Yellow
    Write-Host "8. TestFlight → Internal Testing / External Testing" -ForegroundColor Yellow
    Write-Host "9. App Store → Submit for Review" -ForegroundColor Yellow
    Write-Host ""
} else {
    Write-Error "IPA non trouvé à l'emplacement attendu"
    Write-Warning "Vérifier les erreurs de signing dans Xcode"
    exit 1
}
