$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'

$version = '22.23.1'
$fileName = "node-v$version-win-x64.zip"
$url = "https://nodejs.org/dist/v$version/$fileName"
$expectedHash = '7DF0BC9375723F4A86B3AA1B7CC73342423D9677A8DF4538ACA31A049E309C29'
$projectRoot = Split-Path -Parent $PSScriptRoot
$runtimeRoot = Join-Path $projectRoot 'runtime'
$targetDir = Join-Path $runtimeRoot "node-v$version-win-x64"
$nodeExe = Join-Path $targetDir 'node.exe'
$tempZip = Join-Path $env:TEMP $fileName
$tempExtract = Join-Path $env:TEMP "onlycoin-node-$version"

if (Test-Path $nodeExe) {
    Write-Host "Node.js taşınabilir çalışma ortamı hazır: $nodeExe" -ForegroundColor Green
    exit 0
}

Write-Host ''
Write-Host 'OnlyCoin için gerekli taşınabilir Node.js indiriliyor...' -ForegroundColor Yellow
Write-Host "Kaynak: $url"

New-Item -ItemType Directory -Force -Path $runtimeRoot | Out-Null
if (Test-Path $tempZip) { Remove-Item -Force $tempZip }
if (Test-Path $tempExtract) { Remove-Item -Recurse -Force $tempExtract }

try {
    Invoke-WebRequest -Uri $url -OutFile $tempZip -UseBasicParsing
} catch {
    Write-Host ''
    Write-Host '[HATA] Node.js indirilemedi. İnternet bağlantısını ve güvenlik duvarını kontrol edin.' -ForegroundColor Red
    Write-Host $_.Exception.Message
    exit 1
}

$actualHash = (Get-FileHash -Algorithm SHA256 -Path $tempZip).Hash.ToUpperInvariant()
if ($actualHash -ne $expectedHash) {
    Remove-Item -Force $tempZip -ErrorAction SilentlyContinue
    Write-Host '[HATA] İndirilen çalışma ortamının SHA-256 doğrulaması başarısız.' -ForegroundColor Red
    Write-Host "Beklenen: $expectedHash"
    Write-Host "Bulunan : $actualHash"
    exit 1
}

New-Item -ItemType Directory -Force -Path $tempExtract | Out-Null
Expand-Archive -Path $tempZip -DestinationPath $tempExtract -Force
$extractedDir = Join-Path $tempExtract "node-v$version-win-x64"
if (-not (Test-Path (Join-Path $extractedDir 'node.exe'))) {
    Write-Host '[HATA] İndirilen arşivde node.exe bulunamadı.' -ForegroundColor Red
    exit 1
}

if (Test-Path $targetDir) { Remove-Item -Recurse -Force $targetDir }
Move-Item -Path $extractedDir -Destination $targetDir
Remove-Item -Force $tempZip -ErrorAction SilentlyContinue
Remove-Item -Recurse -Force $tempExtract -ErrorAction SilentlyContinue

Write-Host ''
Write-Host 'Node.js çalışma ortamı güvenli biçimde kuruldu.' -ForegroundColor Green
Write-Host $nodeExe
