# Entropyk dev launcher — robust, idempotent.
# Starts the Rust API server (port 3030) and the Next.js UI (port 3000),
# kills any stale instances first, waits for both to be reachable.

$ErrorActionPreference = "Continue"
$workspace = "D:\dev1405\Entropyk"
$uiDir = "$workspace\apps\web"
$apiLog = "$workspace\server.log"
$uiLog = "$workspace\apps\web\next-dev.log"

function Stop-Port($port) {
    Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue | ForEach-Object {
        try { Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue } catch {}
    }
}

function Wait-Http($url, $timeoutSec = 60) {
    $deadline = (Get-Date).AddSeconds($timeoutSec)
    while ((Get-Date) -lt $deadline) {
        try {
            $r = Invoke-WebRequest -Uri $url -UseBasicParsing -TimeoutSec 3
            if ($r.StatusCode -lt 500) { return $true }
        } catch {}
        Start-Sleep -Seconds 1
    }
    return $false
}

Write-Host "=== Entropyk launcher ===" -ForegroundColor Cyan

# 1. Kill anything stale on 3030 and 3000
Write-Host "[1/5] Killing stale processes on :3030 and :3000..." -ForegroundColor Yellow
Get-CimInstance Win32_Process | Where-Object {
    $_.Name -in @("ui-server.exe") -or
    ($_.CommandLine -match "next dev" -and $_.CommandLine -match "apps.web") -or
    ($_.CommandLine -match "cargo.*entropyk-demo.*ui-server")
} | ForEach-Object {
    Write-Host "  killing PID $($_.ProcessId) ($($_.Name))" -ForegroundColor DarkGray
    try { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue } catch {}
}
Stop-Port 3030
Stop-Port 3000
Start-Sleep -Seconds 2

# 2. Build the API server (debug = ~10s)
Write-Host "[2/5] Building Rust API server..." -ForegroundColor Yellow
$build = Start-Process -FilePath "cargo" -ArgumentList "build","--package","entropyk-demo","--bin","ui-server" -WorkingDirectory $workspace -PassThru -NoNewWindow -Wait
if ($build.ExitCode -ne 0) {
    Write-Host "  BUILD FAILED (exit $($build.ExitCode))" -ForegroundColor Red
    exit 1
}
Write-Host "  build OK" -ForegroundColor Green

# 3. Start Rust API server (detached, with log redirect)
Write-Host "[3/5] Starting Rust API server on :3030..." -ForegroundColor Yellow
Remove-Item $apiLog -Force -ErrorAction SilentlyContinue
$apiProc = Start-Process -FilePath "$workspace\target\debug\ui-server.exe" `
    -WorkingDirectory $workspace `
    -RedirectStandardOutput $apiLog `
    -RedirectStandardError "$workspace\server-err.log" `
    -PassThru -WindowStyle Hidden
Write-Host "  PID $($apiProc.Id), waiting for health..." -ForegroundColor DarkGray

if (-not (Wait-Http "http://localhost:3030/api/health" 30)) {
    Write-Host "  API server failed to start! Log:" -ForegroundColor Red
    Get-Content $apiLog -Tail 20 -ErrorAction SilentlyContinue
    exit 1
}
Write-Host "  API server UP on :3030" -ForegroundColor Green

# 4. Start Next.js dev server
Write-Host "[4/5] Starting Next.js dev server on :3000..." -ForegroundColor Yellow
Remove-Item $uiLog -Force -ErrorAction SilentlyContinue
$uiProc = Start-Process -FilePath "cmd" -ArgumentList "/c","npm run dev > `"$uiLog`" 2>&1" `
    -WorkingDirectory $uiDir `
    -PassThru -WindowStyle Hidden
Write-Host "  PID $($uiProc.Id), waiting for UI..." -ForegroundColor DarkGray

if (-not (Wait-Http "http://localhost:3000" 60)) {
    Write-Host "  UI failed to start! Log:" -ForegroundColor Red
    Get-Content $uiLog -Tail 20 -ErrorAction SilentlyContinue
    exit 1
}
Write-Host "  UI UP on :3000" -ForegroundColor Green

# 5. Status
Write-Host "[5/5] Final status:" -ForegroundColor Yellow
try { $api = Invoke-WebRequest "http://localhost:3030/api/health" -UseBasicParsing -TimeoutSec 3; Write-Host "  API :3030 -> HTTP $($api.StatusCode)" -ForegroundColor Green } catch { Write-Host "  API :3030 -> DOWN" -ForegroundColor Red }
try { $ui = Invoke-WebRequest "http://localhost:3000" -UseBasicParsing -TimeoutSec 3; Write-Host "  UI  :3000 -> HTTP $($ui.StatusCode)" -ForegroundColor Green } catch { Write-Host "  UI  :3000 -> DOWN" -ForegroundColor Red }

Write-Host ""
Write-Host "Both servers running." -ForegroundColor Green
Write-Host "  UI:  http://localhost:3000" -ForegroundColor White
Write-Host "  API: http://localhost:3030/api/health" -ForegroundColor White
Write-Host ""
Write-Host "Logs:" -ForegroundColor DarkGray
Write-Host "  API: $apiLog" -ForegroundColor DarkGray
Write-Host "  UI:  $uiLog" -ForegroundColor DarkGray
Write-Host ""
Write-Host "Open http://localhost:3000 in your browser." -ForegroundColor Cyan
