# check-update.ps1 - Lightweight startup update checker for node-win64
# Exit codes: 0 = no update needed, 1 = update applied (caller should re-launch)
param()

$baseUrl = "https://download.zxiaoming.com/proxy-node-win64"
$versionFile = Join-Path $PSScriptRoot "version.txt"

# Read current local version
if (-not (Test-Path $versionFile)) { exit 0 }
$currentVersionStr = (Get-Content $versionFile -First 1).Trim()
if ([string]::IsNullOrWhiteSpace($currentVersionStr)) { exit 0 }

Write-Host "[update] Current version: $currentVersionStr"

try {
    # Scrape the server directory listing for available versions
    $dirHtml = (Invoke-WebRequest -Uri "$baseUrl/" -UseBasicParsing -TimeoutSec 5).Content
    $regex = 'node-win64\.(v[0-9\.]+)\.zip'
    $found = [regex]::Matches($dirHtml, $regex)
    if ($found.Count -eq 0) {
        Write-Host "[update] No packages found on server, skipping."
        exit 0
    }

    $versions = $found | ForEach-Object { $_.Groups[1].Value } | Select-Object -Unique
    $sorted = @($versions | Sort-Object { [version]($_.TrimStart('v')) } -Descending)
    $latestVersionStr = $sorted[0]

    $currentVer = [version]($currentVersionStr.TrimStart('v'))
    $latestVer = [version]($latestVersionStr.TrimStart('v'))

    if ($latestVer -le $currentVer) {
        Write-Host "[update] Already up to date."
        exit 0
    }

    Write-Host "[update] Update available: $currentVersionStr -> $latestVersionStr" -ForegroundColor Yellow

    # Download the new package
    $zipUrl = "$baseUrl/node-win64.$latestVersionStr.zip"
    $zipPath = Join-Path $env:TEMP "ai_network_update_$latestVersionStr.zip"
    Write-Host "[update] Downloading $zipUrl..."
    Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing -TimeoutSec 120

    # Extract over the install directory (parent of bin/)
    $installDir = Split-Path $PSScriptRoot -Parent
    Write-Host "[update] Extracting to $installDir..."
    Expand-Archive -Path $zipPath -DestinationPath $installDir -Force

    # Cleanup temp file
    Remove-Item $zipPath -Force -ErrorAction SilentlyContinue

    Write-Host "[update] Updated to $latestVersionStr successfully!" -ForegroundColor Green
    exit 1  # Signal caller to re-launch with updated files
} catch {
    Write-Host "[update] Check failed: $($_.Exception.Message)" -ForegroundColor DarkGray
    Write-Host "[update] Continuing with current version."
    exit 0
}
