# serve.ps1 - development server launcher
Write-Host "=== Start Dev Server ===" -ForegroundColor Cyan
Write-Host ""

if (-not (Test-Path "public/wasm/smart_math.js")) {
    Write-Host "[!] WASM output not found, building first..." -ForegroundColor Yellow
    & "$PSScriptRoot\build.ps1"

    if (-not (Test-Path "public/wasm/smart_math.js")) {
        Write-Host "[x] Build failed, cannot start server" -ForegroundColor Red
        exit 1
    }
}

$pythonCommand = $null
$pythonCandidates = @(
    "python",
    "py",
    "python3",
    "C:\Python39\python.exe",
    "C:\Python38\python.exe",
    "C:\Python37\python.exe"
)

foreach ($candidate in $pythonCandidates) {
    try {
        & $candidate --version 2>&1 | Out-Null
        if ($LASTEXITCODE -eq 0) {
            $pythonCommand = $candidate
            Write-Host "[ok] Python found: $candidate" -ForegroundColor Green
            break
        }
    } catch {
        continue
    }
}

if (-not $pythonCommand) {
    Write-Host "[x] Python 3.7+ not found in PATH" -ForegroundColor Red
    exit 1
}

$publicDir = Resolve-Path "public"

Write-Host "[ ] Starting dev server..." -ForegroundColor Cyan
Write-Host ""
Write-Host "Server info:" -ForegroundColor White
Write-Host " - URL: http://localhost:8080/index.html" -ForegroundColor Cyan
Write-Host " - Root: $publicDir" -ForegroundColor Gray
Write-Host " - Home: /index.html" -ForegroundColor Gray
Write-Host " - Stop: Ctrl+C" -ForegroundColor Yellow
Write-Host ""

Set-Location $publicDir
& $pythonCommand -m http.server 8080
