# Start Ninja Nexus in SAFE overlay POC mode.
# Does NOT change registry, shell, or require admin.
param(
  [string]$InstallRoot = $PSScriptRoot
)

$ErrorActionPreference = "Stop"
$InstallRoot = (Resolve-Path $InstallRoot).Path
$identityDir = Join-Path $InstallRoot "identity"
$shellDir = Join-Path $InstallRoot "shell"
$logsDir = Join-Path $InstallRoot "logs"
$pidFile = Join-Path $logsDir "nexus-poc.pids.json"

if (-not (Test-Path (Join-Path $shellDir "NexusShell.exe"))) {
  throw "NexusShell.exe not found. Extract the full package to e.g. C:\NinjaNexusPOC"
}

New-Item -ItemType Directory -Path $logsDir -Force | Out-Null

# Stop any previous POC instance
& (Join-Path $InstallRoot "STOP-NEXUS.ps1") -InstallRoot $InstallRoot -ErrorAction SilentlyContinue

Write-Host "Starting Nexus Identity on http://localhost:5050 ..." -ForegroundColor Cyan
$identityExe = Join-Path $identityDir "NexusIdentity.Api.exe"
$identityArgs = @("--urls", "http://localhost:5050")
$dataDir = Join-Path $InstallRoot "data\identity"
New-Item -ItemType Directory -Path $dataDir -Force | Out-Null
$dbPath = Join-Path $dataDir "nexus-identity.db"
$identityEnv = @{ NEXUS_DB_CONNECTION = "Data Source=$dbPath" }

$identityProc = Start-Process -FilePath $identityExe -WorkingDirectory $identityDir `
  -ArgumentList $identityArgs -PassThru -WindowStyle Hidden `
  -Environment $identityEnv `
  -RedirectStandardOutput (Join-Path $logsDir "identity.log") `
  -RedirectStandardError (Join-Path $logsDir "identity.err.log")

Start-Sleep -Seconds 3
try {
  $health = Invoke-RestMethod -Uri "http://localhost:5050/health" -TimeoutSec 10
  Write-Host "Identity health: $($health.status)" -ForegroundColor Green
} catch {
  Write-Host "Warning: Identity not ready yet — waiting 5s..." -ForegroundColor Yellow
  Start-Sleep -Seconds 5
}

Write-Host "Starting Nexus Shell (--safe-poc overlay mode)..." -ForegroundColor Cyan
Write-Host "SAFE POC: No Windows shell replacement. Lockdown applies inside Shell only." -ForegroundColor Yellow

$shellExe = Join-Path $shellDir "NexusShell.exe"
$shellProc = Start-Process -FilePath $shellExe -WorkingDirectory $shellDir `
  -ArgumentList @("--safe-poc") -PassThru

@{
  startedAt = (Get-Date).ToUniversalTime().ToString("o")
  installRoot = $InstallRoot
  identityPid = $identityProc.Id
  shellPid = $shellProc.Id
  mode = "safe-poc"
} | ConvertTo-Json | Set-Content -LiteralPath $pidFile -Encoding UTF8

Write-Host ""
Write-Host "Nexus Shell PID: $($shellProc.Id)" -ForegroundColor Green
Write-Host "Identity PID:    $($identityProc.Id)" -ForegroundColor Green
Write-Host "Login: user@nexus.local / NexusUser1!" -ForegroundColor Green
Write-Host "Developer Console: Ctrl+Shift+Alt+N (admin@nexus.local)" -ForegroundColor Green
Write-Host "Stop with: .\STOP-NEXUS.ps1" -ForegroundColor Green
