$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $PSScriptRoot
$logDir = Join-Path $root "mcp-server"
$outLog = Join-Path $logDir "ai-mcp.out.log"
$errLog = Join-Path $logDir "ai-mcp.err.log"

Set-Location $root
npm run kb:build

$existing = Get-NetTCPConnection -LocalPort 3100 -State Listen -ErrorAction SilentlyContinue
if ($existing) {
  Write-Output "AI MCP service already listening on port 3100."
  exit 0
}

Start-Process -FilePath "node" -ArgumentList "mcp-server/server.js" -WorkingDirectory $root -RedirectStandardOutput $outLog -RedirectStandardError $errLog -WindowStyle Hidden
Start-Sleep -Seconds 2
Write-Output "AI MCP service started: http://127.0.0.1:3100"
