$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$runtime = Join-Path $root 'Runtime'
New-Item -ItemType Directory -Force -Path $runtime | Out-Null

function Download-VerifiedFile {
    param([string]$Url,[string]$Destination,[string]$Sha256)
    Write-Host "Downloading $Url"
    Invoke-WebRequest -UseBasicParsing -Uri $Url -OutFile $Destination
    $actual=(Get-FileHash -Algorithm SHA256 -Path $Destination).Hash.ToLowerInvariant()
    if($actual -ne $Sha256.ToLowerInvariant()) { Remove-Item $Destination -Force; throw "Hash verification failed. Expected $Sha256; received $actual" }
}

# AutoHotkey v2.0.26 portable runtime.
$ahkDir=Join-Path $runtime 'AutoHotkey'
$ahkExe=Join-Path $ahkDir 'v2\AutoHotkey64.exe'
if(!(Test-Path $ahkExe)) {
    $zip=Join-Path $env:TEMP 'AutoHotkey_2.0.26.zip'
    Download-VerifiedFile 'https://github.com/AutoHotkey/AutoHotkey/releases/download/v2.0.26/AutoHotkey_2.0.26.zip' $zip '43522AA3122A57784AC5DB30ABF85C2244475C36ACD7796E2C993355F9E926AE'
    if(Test-Path $ahkDir){Remove-Item $ahkDir -Recurse -Force}
    Expand-Archive -Path $zip -DestinationPath $ahkDir -Force
    Remove-Item $zip -Force

    # Releases have changed folder layout over time. Normalize the executable
    # into Runtime\AutoHotkey\v2 so every launcher has one stable target.
    $foundAhk = Get-ChildItem -Path $ahkDir -Filter 'AutoHotkey64.exe' -File -Recurse | Select-Object -First 1
    if(-not $foundAhk){ throw "AutoHotkey archive extracted, but AutoHotkey64.exe was not found." }
    $normalizedAhkDir = Join-Path $ahkDir 'v2'
    New-Item -ItemType Directory -Force -Path $normalizedAhkDir | Out-Null
    $normalizedAhkExe = Join-Path $normalizedAhkDir 'AutoHotkey64.exe'
    if($foundAhk.FullName -ne $normalizedAhkExe){
      Copy-Item -Path $foundAhk.FullName -Destination $normalizedAhkExe -Force
    }
}
if(!(Test-Path $ahkExe)){ throw "AutoHotkey runtime setup failed: $ahkExe is missing." }

# CPython 3.13.14 embedded runtime.
$pyDir=Join-Path $runtime 'Python'
$pyExe=Join-Path $pyDir 'python.exe'
if(!(Test-Path $pyExe)) {
    $zip=Join-Path $env:TEMP 'python-3.13.14-embed-amd64.zip'
    Download-VerifiedFile 'https://www.python.org/ftp/python/3.13.14/python-3.13.14-embed-amd64.zip' $zip '90B4E5B9898B72D744650524BFF92377C367F44BD5FBD09E3148656C080AD907'
    if(Test-Path $pyDir){Remove-Item $pyDir -Recurse -Force}
    New-Item -ItemType Directory -Force -Path $pyDir | Out-Null
    Expand-Archive -Path $zip -DestinationPath $pyDir -Force
    Remove-Item $zip -Force
    $pth=Get-ChildItem $pyDir -Filter 'python*._pth' | Select-Object -First 1
    if($pth){
      $lines=Get-Content $pth.FullName | Where-Object { $_ -ne '#import site' -and $_ -ne 'import site' }
      $lines += 'Lib\site-packages'
      $lines += 'import site'
      Set-Content -Path $pth.FullName -Value $lines -Encoding Ascii
    }
}

$site=Join-Path $pyDir 'Lib\site-packages'
New-Item -ItemType Directory -Force -Path $site | Out-Null
$vendor=Join-Path $root 'ClinicalReasoningDatabase\vendor\pypdf'
if(Test-Path $vendor){ Copy-Item $vendor (Join-Path $site 'pypdf') -Recurse -Force }

if(!(Test-Path $pyExe)){ throw "Python runtime setup failed: $pyExe is missing." }
Write-Host 'Runtime setup completed and verified.' -ForegroundColor Green
