$ErrorActionPreference = "Stop"
Set-Location $PSScriptRoot

if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
    throw "Docker Desktop is not installed. Install Docker Desktop for Windows first."
}

docker info *> $null
if ($LASTEXITCODE -ne 0) {
    throw "Docker Desktop is not running. Start Docker Desktop and try again."
}

if (-not (Test-Path ".env")) {
    Copy-Item ".env.production.example" ".env"
    Start-Process notepad.exe ".env"
    throw "A new .env file was created. Replace every placeholder, save it, then run this file again."
}

$envText = Get-Content ".env" -Raw
if ($envText -match "replace-with") {
    Start-Process notepad.exe ".env"
    throw "The .env file still contains placeholder passwords. Replace them before startup."
}

$port = 3100
if ($envText -match "(?m)^PRECISION_HTTP_PORT=(\d+)\s*$") {
    $port = [int]$Matches[1]
}

docker compose up -d --build
if ($LASTEXITCODE -ne 0) {
    throw "Docker startup failed. Run 'docker compose logs' to inspect the error."
}

$addresses = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue |
    Where-Object { $_.IPAddress -notmatch "^(127\.|169\.254\.)" } |
    Select-Object -ExpandProperty IPAddress -Unique

Write-Host ""
Write-Host "Accuracy Retention Evaluation System is running." -ForegroundColor Green
Write-Host "Local: http://localhost:$port"
foreach ($address in $addresses) {
    Write-Host "LAN:   http://${address}:$port"
}
Write-Host "If another computer cannot connect, run configure_lan_firewall.ps1 as Administrator."
Start-Process "http://localhost:$port"
