# Restart the WLED Screen Controller server
# Stop any running instance
$procs = Get-CimInstance Win32_Process -Filter "Name='python.exe'" |
    Where-Object { $_.CommandLine -like '*wled_controller.main*' }
foreach ($p in $procs) {
    Write-Host "Stopping server (PID $($p.ProcessId))..."
    Stop-Process -Id $p.ProcessId -Force -ErrorAction SilentlyContinue
}
if ($procs) { Start-Sleep -Seconds 2 }

# Merge registry PATH with current PATH so newly-installed tools (e.g. scrcpy) 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"
        }
    }
}

# Start server detached
Write-Host "Starting server..."
Start-Process -FilePath python -ArgumentList '-m', 'wled_controller.main' `
    -WorkingDirectory 'c:\Users\Alexei\Documents\wled-screen-controller\server' `
    -WindowStyle Hidden

Start-Sleep -Seconds 3

# Verify it's running
$check = Get-CimInstance Win32_Process -Filter "Name='python.exe'" |
    Where-Object { $_.CommandLine -like '*wled_controller.main*' }
if ($check) {
    Write-Host "Server started (PID $($check[0].ProcessId))"
} else {
    Write-Host "WARNING: Server does not appear to be running!"
}
