# CNPERP Local LAN Server — keeps running until this window is closed.
param(
    [string]$InstallRoot = "",
    [int]$Port = 8010
)

$ErrorActionPreference = "Stop"

function Get-InstallRoot {
    if ($InstallRoot -and (Test-Path $InstallRoot)) { return (Resolve-Path $InstallRoot).Path }
    $here = $PSScriptRoot
    if (-not $here) {
        $here = Split-Path -Parent $PSCommandPath
    }
    $candidate = (Resolve-Path (Join-Path $here "..\..")).Path
    if (Test-Path (Join-Path $candidate "app\main.py")) { return $candidate }
    throw "Cannot find CNPERP install root. Re-run Install-CNPERP-Local.ps1"
}

function Get-LanIPv4 {
    try {
        $ips = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
            Where-Object { $_.IPAddress -notmatch '^127\.' -and $_.PrefixOrigin -ne 'WellKnown' } |
            Select-Object -ExpandProperty IPAddress
        if ($ips) { return $ips[0] }
    } catch { }
    return $null
}

$Root = Get-InstallRoot
Set-Location $Root

$venvPython = Join-Path $Root ".venv\Scripts\python.exe"
$venvUvicorn = Join-Path $Root ".venv\Scripts\uvicorn.exe"
if (-not (Test-Path $venvUvicorn)) {
    Write-Host "Virtual environment not found. Run Install-CNPERP-Local.ps1 first." -ForegroundColor Red
    pause
    exit 1
}

# Load port from .env if present
$envFile = Join-Path $Root ".env"
if (Test-Path $envFile) {
    $m = Select-String -Path $envFile -Pattern '^\s*APP_PORT\s*=\s*(\d+)' | Select-Object -First 1
    if ($m) { $Port = [int]$m.Matches.Groups[1].Value }
}

$lanIp = Get-LanIPv4
$hostLine = if ($lanIp) { "http://${lanIp}:$Port" } else { "http://localhost:$Port" }

Write-Host ""
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  CNPERP Local Server" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  This PC:    http://localhost:$Port" -ForegroundColor Green
if ($lanIp) {
    Write-Host "  LAN users:  $hostLine" -ForegroundColor Green
    Write-Host "  Setup:      $hostLine/setup" -ForegroundColor Yellow
}
Write-Host ""
Write-Host "  Keep this window open while users are connected." -ForegroundColor Gray
Write-Host "  Press Ctrl+C to stop the server." -ForegroundColor Gray
Write-Host ""

$logDir = Join-Path $Root "logs"
if (-not (Test-Path $logDir)) { New-Item -ItemType Directory -Path $logDir | Out-Null }

& $venvUvicorn app.main:app --host 0.0.0.0 --port $Port --workers 1
