#Requires -Version 5.1
<#
.SYNOPSIS
    ImajViewer Windows Build & Installer Pipeline

.DESCRIPTION
    Tek komutla Flutter Windows build + Inno Setup installer olusturur.
    Sirali olarak:
      1. flutter pub get
      2. flutter build windows --release
      3. Inno Setup ile .exe installer olusturma

.PARAMETER Configuration
    Build konfigurasyonu: 'Release' (varsayilan) veya 'Debug'

.PARAMETER SkipInno
    Inno Setup adimini atlar (sadece Flutter build yapar)

.PARAMETER Clean
    Build oncesi 'flutter clean' calistirir

.EXAMPLE
    .\build-windows.ps1
    .\build-windows.ps1 -Configuration Debug
    .\build-windows.ps1 -SkipInno
    .\build-windows.ps1 -Clean -Configuration Release
#>

param(
    [ValidateSet('Release', 'Debug')]
    [string]$Configuration = 'Release',

    [switch]$SkipInno,
    [switch]$Clean
)

# Renkli cikti
function Write-Step { param([string]$Msg) Write-Host "`n>> $Msg" -ForegroundColor Cyan }
function Write-Ok   { param([string]$Msg) Write-Host "   [OK] $Msg" -ForegroundColor Green }
function Write-Err  { param([string]$Msg) Write-Host "   [X]  $Msg" -ForegroundColor Red; exit 1 }
function Write-Warn { param([string]$Msg) Write-Host "   [!]  $Msg" -ForegroundColor Yellow }

$ErrorActionPreference = 'Stop'
$ProjectRoot = Split-Path -Parent $MyInvocation.MyCommand.Path

Write-Host "=" * 60 -ForegroundColor White
Write-Host "  ImajViewer Windows Build Pipeline" -ForegroundColor White
Write-Host "=" * 60 -ForegroundColor White
Write-Host "  Configuration : $Configuration" -ForegroundColor Gray
Write-Host "  Project Root  : $ProjectRoot" -ForegroundColor Gray
Write-Host ""

Set-Location $ProjectRoot

# ── On kosullar ──────────────────────────────────────────────
Write-Step "On kosullar kontrol ediliyor..."

# Flutter
if (-not (Get-Command flutter -ErrorAction SilentlyContinue)) {
    Write-Err "Flutter SDK bulunamadi. PATH'e ekleyin veya https://docs.flutter.dev/get-started/install/windows adresinden kurun."
}
Write-Ok "Flutter: $(flutter --version 2>&1 | Select-String 'Flutter' | Select-Object -First 1)"

# Visual Studio / MSVC
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
if (Test-Path $vswhere) {
    $vsInstall = & $vswhere -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath 2>$null
    if ($vsInstall) {
        Write-Ok "Visual Studio C++ tools bulundu: $vsInstall"
    } else {
        Write-Warn "Visual Studio C++ tools bulunamadi. 'Desktop development with C++' workload'unu kurun."
    }
} else {
    Write-Warn "vswhere bulunamadi. Visual Studio Build Tools kurulu olabilir mi kontrol edin."
}

# CMake
if (Get-Command cmake -ErrorAction SilentlyContinue) {
    Write-Ok "CMake: $(cmake --version 2>&1 | Select-Object -First 1)"
} else {
    Write-Warn "CMake PATH'te bulunamadi. Flutter icin genelde gerekli degildir."
}

# Inno Setup
if (-not $SkipInno) {
    $isccPaths = @(
        "C:\Program Files (x86)\Inno Setup 6\ISCC.exe",
        "C:\Program Files\Inno Setup 6\ISCC.exe",
        "C:\Users\$env:USERNAME\AppData\Local\Programs\Inno Setup 6\ISCC.exe"
    )
    $iscc = $isccPaths | Where-Object { Test-Path $_ } | Select-Object -First 1
    if ($iscc) {
        Write-Ok "Inno Setup: $iscc"
    } else {
        Write-Err "Inno Setup 6 bulunamadi. http://www.jrsoftware.org/isdl.php adresinden kurun."
    }
}

# ── Adim 1: flutter clean (opsiyonel) ──────────────────────
if ($Clean) {
    Write-Step "Adim 1/3: flutter clean"
    flutter clean 2>&1 | Out-Null
    Write-Ok "Clean tamamlandi"
}

# ── Adim 2: flutter pub get ────────────────────────────────
Write-Step "Adim 2/3: flutter pub get"
$result = flutter pub get 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Host $result -ForegroundColor Red
    Write-Err "flutter pub get basarisiz!"
}
Write-Ok "Bağımlilikler indirildi"

# ── Adim 3: flutter build windows ──────────────────────────
Write-Step "Adim 3/3: flutter build windows --$Configuration"
$buildArgs = @('build', 'windows', "--$Configuration")
$result = flutter @buildArgs 2>&1
if ($LASTEXITCODE -ne 0) {
    Write-Host $result -ForegroundColor Red
    Write-Err "Flutter build basarisiz! flutter doctor ile sorunlari kontrol edin."
}

$buildOutput = Join-Path $ProjectRoot "build\windows\x64\runner\$Configuration"
if (-not (Test-Path (Join-Path $buildOutput "imajviewer.exe"))) {
    Write-Err "Build cikti dosyasi bulunamadi: $buildOutput\imajviewer.exe"
}
Write-Ok "Build tamamlandi: $buildOutput"

# ── Adim 4: Inno Setup (opsiyonel) ────────────────────────
if (-not $SkipInno) {
    Write-Step "Inno Setup ile installer olusturuluyor..."
    
    $installerScript = Join-Path $ProjectRoot "windows\installer.iss"
    if (-not (Test-Path $installerScript)) {
        Write-Err "Installer scripti bulunamadi: $installerScript"
    }

    $distDir = Join-Path $ProjectRoot "dist"
    New-Item -ItemType Directory -Force -Path $distDir | Out-Null

    & $iscc $installerScript 2>&1
    if ($LASTEXITCODE -ne 0) {
        Write-Err "Inno Setup derleme basarisiz!"
    }

    $setupExe = Get-ChildItem -Path $distDir -Filter "imajviewer_setup_*.exe" | Select-Object -First 1
    if ($setupExe) {
        $sizeMB = [math]::Round($setupExe.Length / 1MB, 2)
        Write-Ok "Installer olusturuldu: $($setupExe.FullName) ($sizeMB MB)"
    } else {
        Write-Warn "Installer dosyasi dist/ dizininde bulunamadi."
    }
}

# ── Tamamlandı ──────────────────────────────────────────────
Write-Host ""
Write-Host ("=" * 60) -ForegroundColor Green
Write-Host "  Build tamamlandi!" -ForegroundColor Green
Write-Host "  Cikti: $buildOutput" -ForegroundColor Green
if (-not $SkipInno) {
    Write-Host "  Installer: dist\imajviewer_setup_*.exe" -ForegroundColor Green
}
Write-Host ("=" * 60) -ForegroundColor Green
Write-Host ""
