# rmtPocketWatcher Self-Extracting Executable Builder
# Creates a single .exe that extracts and runs the app

$ErrorActionPreference = "Stop"

$7zPath = "${env:ProgramFiles}\7-Zip\7z.exe"
if (-not (Test-Path $7zPath)) {
    $7zPath = "${env:ProgramFiles(x86)}\7-Zip\7z.exe"
}
if (-not (Test-Path $7zPath)) {
    Write-Error "7-Zip not found. Please install 7-Zip from https://7-zip.org"
    exit 1
}

$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$StandaloneDir = Join-Path $ScriptDir "build\windows\standalone"
$OutputDir = Join-Path $ScriptDir "build\windows\sfx"
$SfxModule = "${env:ProgramFiles}\7-Zip\7z.sfx"
$PubspecPath = Join-Path $ScriptDir "pubspec.yaml"

if (-not (Test-Path $StandaloneDir)) {
    Write-Error "Standalone build not found. Run build_windows.ps1 first."
    exit 1
}

Write-Host "Creating self-extracting executable..." -ForegroundColor Green

# Create output directory
if (Test-Path $OutputDir) { Remove-Item -Recurse -Force $OutputDir }
New-Item -ItemType Directory -Path $OutputDir -Force | Out-Null

# Create SFX config file - silent extract to AppData and run
$SfxConfig = @"
;!@Install@!UTF-8!
Title="rmtPocketWatcher"
InstallPath="%LOCALAPPDATA%\\rmtPocketWatcher"
RunProgram="rmtpocketwatcher.exe"
GUIMode="2"
OverwriteMode="2"
;!@InstallEnd@!
"@

$SfxConfigPath = "$OutputDir\sfx_config.txt"
$SfxConfig | Out-File -FilePath $SfxConfigPath -Encoding UTF8

# Create 7z archive of standalone folder
$ArchivePath = "$OutputDir\app.7z"
Write-Host "Compressing application..." -ForegroundColor Yellow
& $7zPath a -t7z -mx=9 -mf=BCJ2 -r $ArchivePath "$StandaloneDir\*" | Out-Null

if (-not (Test-Path $ArchivePath)) {
    Write-Error "Failed to create archive"
    exit 1
}

# Combine SFX module + config + archive
$Version = (Select-String -Path $PubspecPath -Pattern "^version: (.+)$").Matches[0].Groups[1].Value -replace '\+.*', ''
$SfxExePath = "$OutputDir\rmtPocketWatcher-v$Version-Portable.exe"

Write-Host "Building self-extracting executable..." -ForegroundColor Yellow

# Read binary files and concatenate
$sfxBytes = [System.IO.File]::ReadAllBytes($SfxModule)
$configBytes = [System.IO.File]::ReadAllBytes($SfxConfigPath)
$archiveBytes = [System.IO.File]::ReadAllBytes($ArchivePath)

$outputStream = [System.IO.File]::Create($SfxExePath)
$outputStream.Write($sfxBytes, 0, $sfxBytes.Length)
$outputStream.Write($configBytes, 0, $configBytes.Length)
$outputStream.Write($archiveBytes, 0, $archiveBytes.Length)
$outputStream.Close()

# Cleanup temp files
Remove-Item $SfxConfigPath -Force
Remove-Item $ArchivePath -Force

$FileSize = [math]::Round((Get-Item $SfxExePath).Length / 1MB, 2)
Write-Host "`n✅ Self-extracting executable created!" -ForegroundColor Green
Write-Host "   File: $SfxExePath" -ForegroundColor Cyan
Write-Host "   Size: $FileSize MB" -ForegroundColor Cyan
Write-Host "`nThis single .exe can be distributed and run on any Windows PC." -ForegroundColor Yellow
