param(
  [string]$Distro = "Ubuntu",
  [string]$InstallRoot = "$env:LOCALAPPDATA\ResearchPadAgent"
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$LogDir = Join-Path $InstallRoot "logs"
New-Item -ItemType Directory -Force -Path $LogDir | Out-Null

function Write-Ok($Message) { Write-Host "OK  $Message" -ForegroundColor Green }
function Write-Warn($Message) { Write-Host "WARN $Message" -ForegroundColor Yellow }

function Test-Port([int]$Port) {
  try {
    $conn = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue | Select-Object -First 1
    return $null -ne $conn
  } catch {
    return $false
  }
}

function Convert-ToWslPath([string]$Path) {
  $full = [System.IO.Path]::GetFullPath($Path)
  $drive = $full.Substring(0, 1).ToLowerInvariant()
  $rest = $full.Substring(2).Replace("\", "/")
  return "/mnt/$drive$rest"
}

function Find-Node {
  $cmd = Get-Command node.exe -ErrorAction SilentlyContinue
  if ($cmd) { return $cmd.Source }
  $candidate = Join-Path $InstallRoot "node.exe"
  if (Test-Path $candidate) { return $candidate }
  throw "node.exe not found. Install Node.js LTS and rerun install.ps1."
}

Write-Host "Starting ResearchPad Agent Windows services..."

$wslScript = Join-Path $InstallRoot "wsl\start-wsl-agent.sh"
if (-not (Test-Path $wslScript)) { throw "Missing WSL start script: $wslScript" }
$wslScriptPath = Convert-ToWslPath $wslScript

& wsl.exe -d $Distro -- bash "$wslScriptPath"
if ($LASTEXITCODE -ne 0) { throw "Failed to start WSL backend." }
Write-Ok "WSL code-server backend requested"

if (Test-Port 8443) {
  Write-Ok "HTTPS proxy already listening on :8443"
} else {
  $node = Find-Node
  $proxyScript = Join-Path $InstallRoot "proxy-httpproxy.js"
  if (-not (Test-Path $proxyScript)) { throw "Missing proxy script: $proxyScript" }

  $stdout = Join-Path $LogDir "https-proxy.out.log"
  $stderr = Join-Path $LogDir "https-proxy.err.log"
  Start-Process -FilePath $node `
    -ArgumentList "`"$proxyScript`"" `
    -WorkingDirectory $InstallRoot `
    -WindowStyle Hidden `
    -RedirectStandardOutput $stdout `
    -RedirectStandardError $stderr
  Start-Sleep -Seconds 2
  if (Test-Port 8443) {
    Write-Ok "HTTPS proxy started on :8443"
  } else {
    Write-Warn "HTTPS proxy did not report :8443 yet. Check $stderr"
  }
}

try {
  [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
  $health = Invoke-WebRequest -UseBasicParsing -TimeoutSec 5 "https://local.researchpad.org:8443/api/healthz"
  if ($health.StatusCode -eq 200) { Write-Ok "Local gateway health check passed" }
} catch {
  Write-Warn "Health check failed; services may still be starting. $($_.Exception.Message)"
}

Write-Host "Open https://agent.researchpad.org/"
