# Restart the Media Server.
#
# Robust against the two ways the server gets started:
#   - Installer build:   %LOCALAPPDATA%\Media Server\media-server.bat
#                        (runs as python.exe -m media_server.main)
#   - Dev editable install: media-server console script on PATH
#                        (runs as media-server.exe)
#
# The old version of this script only killed processes named 'media-server',
# which silently missed the installer-bundled process (named 'python').
# This version kills whatever currently owns the listen port, so it doesn't
# matter how the previous instance was launched.

param(
    [ValidateSet('auto', 'dev', 'installer')]
    [string]$Mode = 'auto',
    [int]$Port = 8765
)

$InstallerLauncher = Join-Path $env:LOCALAPPDATA 'Media Server\media-server.bat'
$InstallerDir = Join-Path $env:LOCALAPPDATA 'Media Server'

# --- Resolve launch mode -----------------------------------------------------
if ($Mode -eq 'auto') {
    if (Test-Path $InstallerLauncher) {
        $Mode = 'installer'
    } else {
        $Mode = 'dev'
    }
}

# --- Stop whatever is listening on the port ---------------------------------
$listenerPids = @()
try {
    $conns = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
    if ($conns) {
        $listenerPids = $conns | Select-Object -ExpandProperty OwningProcess -Unique
    }
} catch {
    # Get-NetTCPConnection unavailable (rare); fall back to netstat parsing
    $listenerPids = & netstat -ano | Select-String ":$Port\s+.*LISTENING" | ForEach-Object {
        ($_ -split '\s+')[-1]
    } | Sort-Object -Unique
}

foreach ($targetPid in $listenerPids) {
    $proc = Get-Process -Id $targetPid -ErrorAction SilentlyContinue
    if ($proc) {
        Write-Host "Stopping listener PID $($proc.Id) ($($proc.ProcessName))..."
        Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
    }
}

# Also kill any orphan media-server.exe instances that didn't bind the port.
$orphans = Get-Process -Name 'media-server' -ErrorAction SilentlyContinue
foreach ($p in $orphans) {
    Write-Host "Stopping orphan media-server PID $($p.Id)..."
    Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue
}

if ($listenerPids -or $orphans) {
    # Allow the OS to release the listen socket from TIME_WAIT.
    Start-Sleep -Seconds 3
}

# --- Start the chosen flavour ------------------------------------------------
if ($Mode -eq 'installer') {
    if (-not (Test-Path $InstallerLauncher)) {
        Write-Error "Installer launcher not found: $InstallerLauncher"
        exit 1
    }
    Write-Host "Starting installer build: $InstallerLauncher"
    Start-Process -FilePath $InstallerLauncher `
        -WorkingDirectory $InstallerDir `
        -WindowStyle Hidden
} else {
    # Merge registry PATH so newly-installed dev tools are visible.
    $regUser = [Environment]::GetEnvironmentVariable('PATH', 'User')
    if ($regUser) {
        $currentDirs = $env:PATH -split ';' | ForEach-Object { $_.TrimEnd('\') }
        foreach ($dir in ($regUser -split ';')) {
            if ($dir -and ($currentDirs -notcontains $dir.TrimEnd('\'))) {
                $env:PATH = "$env:PATH;$dir"
            }
        }
    }
    Write-Host "Starting dev install (PATH media-server)..."
    Start-Process -FilePath 'media-server' `
        -WorkingDirectory 'c:\Users\Alexei\Documents\haos-integration-media-player\media-server' `
        -WindowStyle Hidden
}

Start-Sleep -Seconds 3

# --- Verify it's listening ---------------------------------------------------
$verify = Get-NetTCPConnection -LocalPort $Port -State Listen -ErrorAction SilentlyContinue
if ($verify) {
    $vpid = $verify[0].OwningProcess
    $vproc = Get-Process -Id $vpid -ErrorAction SilentlyContinue
    Write-Host "Server listening on port $Port (PID $vpid, $($vproc.ProcessName))"
} else {
    Write-Warning "Server is not listening on port $Port yet - check logs."
}
