$ErrorActionPreference = 'Stop'
Set-Location $PSScriptRoot

$ExpectedVersion = '1.3.0'
$Port = 4173
$HealthUrl = "http://127.0.0.1:$Port/api/health"
$AppUrl = "http://127.0.0.1:$Port/?version=$ExpectedVersion#home"
$PidFile = Join-Path $PSScriptRoot '.shire-forge.pid'

if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
  Write-Host ""
  Write-Host "SHIRE Marketing Forge Easy needs the free Node.js LTS version." -ForegroundColor Red
  Write-Host "Install Node.js LTS, then run start-windows.bat again." -ForegroundColor Yellow
  Read-Host "Press Enter to close"
  exit 1
}

function Unprotect-Secret([string]$Encrypted) {
  if ([string]::IsNullOrWhiteSpace($Encrypted)) { return '' }
  $secure = ConvertTo-SecureString $Encrypted
  $ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
  try { return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($ptr) }
  finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
}

function Stop-ListenerOnPort([int]$LocalPort) {
  try {
    $connections = Get-NetTCPConnection -LocalPort $LocalPort -State Listen -ErrorAction Stop
    $processIds = $connections | Select-Object -ExpandProperty OwningProcess -Unique
    foreach ($processId in $processIds) {
      if ($processId -and $processId -ne $PID) {
        Stop-Process -Id $processId -Force -ErrorAction SilentlyContinue
      }
    }
    Start-Sleep -Milliseconds 700
  } catch {
    # Older Windows builds may not provide Get-NetTCPConnection. Try the PID file.
    if (Test-Path $PidFile) {
      $savedPid = (Get-Content $PidFile -Raw).Trim()
      if ($savedPid -match '^\d+$') { Stop-Process -Id ([int]$savedPid) -Force -ErrorAction SilentlyContinue }
      Remove-Item $PidFile -Force -ErrorAction SilentlyContinue
      Start-Sleep -Milliseconds 700
    }
  }
}

$configPath = Join-Path $PSScriptRoot 'social-oauth.secure.json'
if (Test-Path $configPath) {
  try {
    $config = Get-Content $configPath -Raw | ConvertFrom-Json
    if ($config.metaAppId) { $env:META_APP_ID = [string]$config.metaAppId }
    if ($config.metaAppSecret) { $env:META_APP_SECRET = Unprotect-Secret ([string]$config.metaAppSecret) }
    if ($config.linkedinClientId) { $env:LINKEDIN_CLIENT_ID = [string]$config.linkedinClientId }
    if ($config.linkedinClientSecret) { $env:LINKEDIN_CLIENT_SECRET = Unprotect-Secret ([string]$config.linkedinClientSecret) }
    if ($config.tiktokClientKey) { $env:TIKTOK_CLIENT_KEY = [string]$config.tiktokClientKey }
    if ($config.tiktokClientSecret) { $env:TIKTOK_CLIENT_SECRET = Unprotect-Secret ([string]$config.tiktokClientSecret) }
    if ($config.googleClientId) { $env:GOOGLE_CLIENT_ID = [string]$config.googleClientId }
    if ($config.googleClientSecret) { $env:GOOGLE_CLIENT_SECRET = Unprotect-Secret ([string]$config.googleClientSecret) }
  } catch {
    Write-Host "The secure social configuration could not be read." -ForegroundColor Red
    Write-Host $_.Exception.Message -ForegroundColor Gray
    Write-Host "Run configure-social-logins-windows.ps1 again." -ForegroundColor Yellow
    Read-Host "Press Enter to close"
    exit 1
  }
}

$health = $null
try { $health = Invoke-RestMethod -Uri $HealthUrl -TimeoutSec 1 } catch {}

if ($health -and [string]$health.version -ne $ExpectedVersion) {
  Write-Host "An older SHIRE Forge server (v$($health.version)) is still running." -ForegroundColor Yellow
  Write-Host "Stopping it so v$ExpectedVersion can open instead..." -ForegroundColor Yellow
  Stop-ListenerOnPort $Port
  $health = $null
}

if (-not $health) {
  $process = Start-Process -FilePath 'node' -ArgumentList 'server.js' -WorkingDirectory $PSScriptRoot -WindowStyle Minimized -PassThru
  Set-Content -Path $PidFile -Value $process.Id -Encoding ascii
  $ready = $false
  for ($attempt = 0; $attempt -lt 20; $attempt += 1) {
    Start-Sleep -Milliseconds 250
    try {
      $health = Invoke-RestMethod -Uri $HealthUrl -TimeoutSec 1
      if ($health -and [string]$health.version -eq $ExpectedVersion) { $ready = $true; break }
    } catch {}
  }
  if (-not $ready) {
    Write-Host "The Forge server did not start correctly." -ForegroundColor Red
    Write-Host "Run node server.js in this folder to see the error." -ForegroundColor Yellow
    Read-Host "Press Enter to close"
    exit 1
  }
}

Write-Host "SHIRE Marketing Forge Easy v$ExpectedVersion is running." -ForegroundColor Green
Start-Process $AppUrl
