$pgDir = "$env:TEMP\pg\pgsql"
$pgData = "$env:TEMP\pg\data"
$pgBin = "$pgDir\bin"
$logFile = "$env:TEMP\pg\logfile"

if (-not (Test-Path "$pgData\postgresql.conf")) {
    Write-Error "PostgreSQL not initialized. Run initdb first."
    exit 1
}

$running = $null -ne (Get-Process -Name "postgres" -ErrorAction SilentlyContinue)
$listening = $null -ne (netstat -ano -p TCP 2>$null | Select-String ":5432.*LISTENING")

if (-not $running -or -not $listening) {
    $existing = Get-Process -Name "postgres" -ErrorAction SilentlyContinue
    if ($existing) { $existing | Stop-Process -Force }
    Start-Sleep -Seconds 1
    Remove-Item "$pgData\postmaster.pid" -Force -ErrorAction SilentlyContinue
    $env:PATH = "$pgBin;$env:PATH"
    Start-Process -FilePath "$pgBin\postgres.exe" -ArgumentList "-D `"$pgData`"" -WindowStyle Hidden
    Start-Sleep -Seconds 3
    Write-Output "PostgreSQL started."
} else {
    Write-Output "PostgreSQL already running on port 5432."
}
