import { pwaAllowedHostsEnvironment } from "./safe-runtime-lib.mjs";

export function developmentRuntimeEnvironment(config, configPath, env = process.env) {
  return {
    ...env,
    ...pwaAllowedHostsEnvironment(config, env),
    CODE_REMOTE_MANAGER_CONFIG_PATH: configPath,
    CODE_REMOTE_MANAGER_DEVELOPER_PRO: "1",
    NODE_ENV: "development",
    VITE_CODE_REMOTE_MANAGER_RUNTIME: "development"
  };
}

export function installedRuntimeCleanupScript() {
  return String.raw`
$ErrorActionPreference = "Stop"
$installRoot = [IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA "Programs\Code Remote Manager"))
$runtimeRoot = [IO.Path]::GetFullPath((Join-Path $env:LOCALAPPDATA "CodeRemoteManager\safe-runtime"))
$runKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run"
Remove-ItemProperty -LiteralPath $runKey -Name "Code Remote Manager Host" -ErrorAction SilentlyContinue
$escapedRuntimeRoot = [regex]::Escape($runtimeRoot)
$runtimeControllers = Get-CimInstance Win32_Process | Where-Object {
  $_.Name -eq "node.exe" -and
  $_.CommandLine -match $escapedRuntimeRoot -and
  $_.CommandLine -match "safe-runtime[\\/]control[\\/]safe-runtime\.mjs"
}
$runtimeControllers | ForEach-Object {
  & taskkill.exe /pid $_.ProcessId /t /f | Out-Null
}
$escapedRoot = [regex]::Escape($installRoot)
$installedProcesses = Get-CimInstance Win32_Process | Where-Object {
  $_.Name -eq "node.exe" -and
  $_.CommandLine -match $escapedRoot -and
  ($_.CommandLine -match "host[\\/]host\.mjs" -or $_.CommandLine -match "app[\\/]backend[\\/]src[\\/]index\.js")
}
$installedProcesses | Sort-Object { if ($_.CommandLine -match "backend") { 0 } else { 1 } } | ForEach-Object {
  Stop-Process -Id $_.ProcessId -ErrorAction SilentlyContinue
}
`;
}
