param(
    [switch]$NoBrowser
)

Set-Location $PSScriptRoot
$ErrorActionPreference = "Stop"
$port = 8765
$url = "http://127.0.0.1:$port/"

function Find-Python {
    $local = Join-Path $PSScriptRoot "runtime\python.exe"
    if (Test-Path $local) { return $local }
    $cmd = Get-Command python -ErrorAction SilentlyContinue
    if ($cmd) { return $cmd.Source }
    $py = Get-Command py -ErrorAction SilentlyContinue
    if ($py) { return "py -3" }
    return $null
}

function Start-PsStaticServer {
    $root = (Resolve-Path $PSScriptRoot).Path
    $listener = New-Object System.Net.HttpListener
    $listener.Prefixes.Add("http://127.0.0.1:$port/")
    $listener.Start()
    Write-Host "PowerShell static server @ $url"
    Write-Host "Root: $root"
    Write-Host "Close this window to stop."
    while ($listener.IsListening) {
        $ctx = $listener.GetContext()
        $req = $ctx.Request
        $res = $ctx.Response
        try {
            $rel = [Uri]::UnescapeDataString($req.Url.AbsolutePath.TrimStart('/'))
            if ([string]::IsNullOrWhiteSpace($rel)) { $rel = "index.html" }
            $full = [System.IO.Path]::GetFullPath((Join-Path $root ($rel -replace '/', '\')))
            if (-not $full.StartsWith($root, [StringComparison]::OrdinalIgnoreCase) -or -not (Test-Path -LiteralPath $full -PathType Leaf)) {
                $res.StatusCode = 404
                $bytes = [Text.Encoding]::UTF8.GetBytes("Not Found")
            } else {
                $ext = [IO.Path]::GetExtension($full).ToLowerInvariant()
                $ctype = switch ($ext) {
                    ".html" { "text/html; charset=utf-8" }
                    ".js"   { "text/javascript; charset=utf-8" }
                    ".css"  { "text/css; charset=utf-8" }
                    ".json" { "application/json; charset=utf-8" }
                    ".svg"  { "image/svg+xml" }
                    ".png"  { "image/png" }
                    default { "application/octet-stream" }
                }
                $bytes = [IO.File]::ReadAllBytes($full)
                $res.ContentType = $ctype
                $res.StatusCode = 200
            }
            $res.ContentLength64 = $bytes.Length
            $res.OutputStream.Write($bytes, 0, $bytes.Length)
        } catch {
            $res.StatusCode = 500
        } finally {
            $res.OutputStream.Close()
        }
    }
}

$py = Find-Python
if (-not $NoBrowser) {
    Start-Process $url
}

Write-Host "DSD-P layout editor"
Write-Host "Open: $url"
Write-Host ""

if ($py) {
    Write-Host "Using: $py"
    if ($py -eq "py -3") {
        & py -3 -m http.server $port
    } else {
        & $py -m http.server $port
    }
} else {
    Write-Host "No Python found; using PowerShell HttpListener fallback."
    Start-PsStaticServer
}
