#Requires -Version 5.1
<#
.SYNOPSIS
  Pre-build step: download gost.exe v3.2.6, verify SHA256, and stage it in
  proxy_chain_manager/_bundled/gost.exe so PyInstaller can bundle it.

.DESCRIPTION
  Runs before scripts\setup_and_build.ps1. After this step, the spec file
  includes _bundled/gost.exe as a data file inside the exe and ensure_gost()
  copies it out to %LOCALAPPDATA% on first run.
#>
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$bundleDir = Join-Path $root "proxy_chain_manager\_bundled"
$bundleExe = Join-Path $bundleDir "gost.exe"
$expectedZipHash = "32f4edf3d94b622e67f1979f6f5de82dac62abc0977772cf96215dd199ef7e7b"
$zipUrl = "https://github.com/go-gost/gost/releases/download/v3.2.6/gost_3.2.6_windows_amd64.zip"

if (-not (Test-Path $bundleDir)) {
    New-Item -ItemType Directory -Path $bundleDir | Out-Null
}

# Skip if already staged and valid
if (Test-Path $bundleExe) {
    Write-Host "Bundled gost.exe already present at $bundleExe"
    exit 0
}

$tempZip = Join-Path $env:TEMP "gost_bundle.zip"
Write-Host "Downloading $zipUrl ..."
Invoke-WebRequest -Uri $zipUrl -OutFile $tempZip -UseBasicParsing

$actualZipHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $tempZip).Hash.ToLower()
if ($actualZipHash -ne $expectedZipHash) {
    Remove-Item -LiteralPath $tempZip -Force -ErrorAction SilentlyContinue
    throw "GOST zip SHA256 mismatch! expected=$expectedZipHash actual=$actualZipHash"
}
Write-Host "Zip SHA256 OK: $actualZipHash"

$tempExtract = Join-Path $env:TEMP "gost_bundle_extract"
if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract }
Expand-Archive -LiteralPath $tempZip -DestinationPath $tempExtract -Force

$extractedExe = Get-ChildItem -Path $tempExtract -Filter "gost.exe" -Recurse | Select-Object -First 1
if (-not $extractedExe) {
    throw "gost.exe not found inside extracted zip"
}

Copy-Item -LiteralPath $extractedExe.FullName -Destination $bundleExe -Force

# Pin the exe hash so runtime can verify the copy that gets dropped to %LOCALAPPDATA%
$exeHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $bundleExe).Hash.ToLower()
"$exeHash" | Out-File -FilePath "$bundleExe.sha256" -Encoding ascii -Force

Remove-Item -LiteralPath $tempZip -Force -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue

Write-Host "Bundled gost.exe: $bundleExe ($exeHash)"
