# rmtPocketWatcher Windows Build Script
# Creates both standalone executable and MSIX installer

param(
    [switch]$Release = $false,
    [switch]$Debug = $false
)

$ErrorActionPreference = "Stop"

# Determine build mode
$BuildMode = if ($Release) { "release" } elseif ($Debug) { "debug" } else { "release" }
$BuildModeCapital = (Get-Culture).TextInfo.ToTitleCase($BuildMode)

Write-Host "Building rmtPocketWatcher for Windows ($BuildModeCapital mode)" -ForegroundColor Green
Write-Host "=============================================" -ForegroundColor Green

# Clean previous builds
Write-Host "Cleaning previous builds..." -ForegroundColor Yellow
flutter clean
if (Test-Path "build") {
    Remove-Item -Recurse -Force "build"
}

# Install dependencies
Write-Host "Installing dependencies..." -ForegroundColor Yellow
flutter pub get

# Build Flutter Windows app
Write-Host "Building Flutter Windows app..." -ForegroundColor Yellow
flutter build windows --$BuildMode

# Check if build was successful
$ExePath = "build\windows\x64\runner\$BuildModeCapital\rmtpocketwatcher.exe"
if (-not (Test-Path $ExePath)) {
    Write-Error "Build failed - executable not found at $ExePath"
    exit 1
}

Write-Host "✅ Flutter build completed successfully" -ForegroundColor Green

# Create standalone executable directory
$StandaloneDir = "build\windows\standalone"
Write-Host "Creating standalone executable package..." -ForegroundColor Yellow

if (Test-Path $StandaloneDir) {
    Remove-Item -Recurse -Force $StandaloneDir
}
New-Item -ItemType Directory -Path $StandaloneDir -Force | Out-Null

# Copy all necessary files for standalone distribution
$SourceDir = "build\windows\x64\runner\$BuildModeCapital"
Copy-Item -Path "$SourceDir\*" -Destination $StandaloneDir -Recurse -Force

# Create version info
$Version = (Select-String -Path "pubspec.yaml" -Pattern "^version: (.+)$").Matches[0].Groups[1].Value -replace '\+.*', ''
$VersionInfo = @"
rmtPocketWatcher v$Version
Lambda Banking Conglomerate
Star Citizen AUEC Price Tracker

Built: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')
Mode: $BuildModeCapital

To run: Double-click rmtpocketwatcher.exe
No installation required - all dependencies included.
"@

$VersionInfo | Out-File -FilePath "$StandaloneDir\VERSION.txt" -Encoding UTF8

Write-Host "✅ Standalone executable created at: $StandaloneDir" -ForegroundColor Green

# Sign the standalone executable
$CertPath = "certificates\rmtPocketWatcher.pfx"
if (Test-Path $CertPath) {
    Write-Host "Signing standalone executable..." -ForegroundColor Yellow
    try {
        .\sign_executable.ps1 -ExePath "$StandaloneDir\rmtpocketwatcher.exe" -Force
    } catch {
        Write-Warning "Failed to sign executable: $($_.Exception.Message)"
        Write-Host "Continuing without signing..." -ForegroundColor Yellow
    }
} else {
    Write-Host "No certificate found - executable will be unsigned" -ForegroundColor Yellow
    Write-Host "Run .\create_certificate.ps1 to create a self-signed certificate" -ForegroundColor Yellow
}

# Create MSIX installer
Write-Host "Creating MSIX installer..." -ForegroundColor Yellow
try {
    # Check for certificate
    $CertPath = "certificates\rmtPocketWatcher.pfx"
    $CertPassword = if ($env:MSIX_CERTIFICATE_PASSWORD) { $env:MSIX_CERTIFICATE_PASSWORD } else { "rmtPocketWatcher2024!" }
    
    if (Test-Path $CertPath) {
        Write-Host "Using certificate for signing: $CertPath" -ForegroundColor Cyan
        $env:MSIX_CERTIFICATE_PATH = $CertPath
        $env:MSIX_CERTIFICATE_PASSWORD = $CertPassword
    } else {
        Write-Host "No certificate found - creating unsigned MSIX" -ForegroundColor Yellow
        Write-Host "Run .\create_certificate.ps1 to create a self-signed certificate" -ForegroundColor Yellow
    }
    
    flutter pub run msix:create
    
    $MsixPath = Get-ChildItem -Path "build\windows\x64\runner\$BuildModeCapital" -Filter "*.msix" | Select-Object -First 1
    if ($MsixPath) {
        Write-Host "✅ MSIX installer created: $($MsixPath.FullName)" -ForegroundColor Green
        
        # Sign the MSIX if certificate exists
        if (Test-Path $CertPath) {
            Write-Host "Signing MSIX installer..." -ForegroundColor Yellow
            try {
                $signtool = "${env:ProgramFiles(x86)}\Windows Kits\10\bin\10.0.22621.0\x64\signtool.exe"
                if (-not (Test-Path $signtool)) {
                    # Try to find signtool in common locations
                    $signtool = Get-ChildItem -Path "${env:ProgramFiles(x86)}\Windows Kits" -Recurse -Name "signtool.exe" | Select-Object -First 1
                    if ($signtool) {
                        $signtool = "${env:ProgramFiles(x86)}\Windows Kits\$signtool"
                    }
                }
                
                if (Test-Path $signtool) {
                    & $signtool sign /f $CertPath /p $CertPassword /fd SHA256 /tr http://timestamp.digicert.com /td SHA256 $MsixPath.FullName
                    if ($LASTEXITCODE -eq 0) {
                        Write-Host "✅ MSIX installer signed successfully" -ForegroundColor Green
                    } else {
                        Write-Warning "Failed to sign MSIX installer"
                    }
                } else {
                    Write-Warning "SignTool not found - install Windows SDK to enable signing"
                }
            } catch {
                Write-Warning "Failed to sign MSIX: $($_.Exception.Message)"
            }
        }
    } else {
        Write-Warning "MSIX installer creation completed but file not found in expected location"
    }
} catch {
    Write-Warning "MSIX installer creation failed: $($_.Exception.Message)"
    Write-Host "Continuing with standalone executable only..." -ForegroundColor Yellow
}

# Create distribution archive
Write-Host "Creating distribution archive..." -ForegroundColor Yellow
$ArchiveName = "rmtPocketWatcher-Windows-v$Version-$BuildMode.zip"
$ArchivePath = "build\$ArchiveName"

if (Test-Path $ArchivePath) {
    Remove-Item $ArchivePath -Force
}

Compress-Archive -Path "$StandaloneDir\*" -DestinationPath $ArchivePath -CompressionLevel Optimal

Write-Host "✅ Distribution archive created: $ArchivePath" -ForegroundColor Green

# Summary
Write-Host "`n🎉 Build completed successfully!" -ForegroundColor Green
Write-Host "=============================================" -ForegroundColor Green
Write-Host "Standalone executable: $StandaloneDir\rmtpocketwatcher.exe" -ForegroundColor Cyan
Write-Host "Distribution archive: $ArchivePath" -ForegroundColor Cyan

if ($MsixPath) {
    Write-Host "MSIX installer: $($MsixPath.FullName)" -ForegroundColor Cyan
}

Write-Host "`nTo test the standalone version:" -ForegroundColor Yellow
Write-Host "  cd $StandaloneDir" -ForegroundColor White
Write-Host "  .\rmtpocketwatcher.exe" -ForegroundColor White

Write-Host "`nTo distribute:" -ForegroundColor Yellow
Write-Host "  - Share the ZIP file: $ArchiveName" -ForegroundColor White
Write-Host "  - Users extract and run rmtpocketwatcher.exe" -ForegroundColor White
if ($MsixPath) {
    Write-Host "  - Or share the MSIX installer for Windows Store-style installation" -ForegroundColor White
}