$ErrorActionPreference = "Stop"

$siteRoot = (Resolve-Path (Join-Path $PSScriptRoot "..")).ProviderPath
$python = "C:\Users\jason\.cache\codex-runtimes\codex-primary-runtime\dependencies\python\python.exe"
$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"
$port = 8793
$pdfPath = Join-Path $siteRoot "Resume_Jason_Eugene_Garrison.pdf"
$docxPath = Join-Path $siteRoot "Resume_Jason_Eugene_Garrison.docx"

if (-not (Test-Path $python)) {
    throw "Bundled Python was not found at $python"
}

if (-not (Test-Path $chrome)) {
    throw "Chrome was not found at $chrome"
}

& $python (Join-Path $PSScriptRoot "generate-resume-docx.py") $siteRoot $docxPath
if ($LASTEXITCODE -ne 0) {
    throw "DOCX generation failed with exit code $LASTEXITCODE"
}

$server = $null
try {
    $server = Start-Process -FilePath $python `
        -ArgumentList @("-m", "http.server", "$port", "--bind", "127.0.0.1", "--directory", $siteRoot) `
        -WorkingDirectory $env:TEMP `
        -WindowStyle Hidden `
        -PassThru

    $url = "http://127.0.0.1:$port/index.html?print=$(Get-Date -Format yyyyMMddHHmmss)"

    $ready = $false
    for ($i = 0; $i -lt 30; $i++) {
        try {
            $response = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 2
            if ($response.StatusCode -eq 200 -and $response.Content -match "Jason Eugene Garrison") {
                $ready = $true
                break
            }
        } catch {
            Start-Sleep -Milliseconds 500
        }
    }

    if (-not $ready) {
        throw "Local resume preview server was not reachable at $url"
    }

    & $chrome `
        --headless=new `
        --disable-gpu `
        --disable-background-networking `
        --disable-sync `
        --metrics-recording-only `
        --no-pdf-header-footer `
        --print-to-pdf="$pdfPath" `
        $url | Out-Null

    if ($LASTEXITCODE -ne 0) {
        throw "PDF generation failed with exit code $LASTEXITCODE"
    }
}
finally {
    if ($server -and -not $server.HasExited) {
        Stop-Process -Id $server.Id -Force
    }
}

& (Join-Path $PSScriptRoot "publish-permissions.ps1")

Write-Host "Updated $pdfPath"
Write-Host "Updated $docxPath"
