param(
  [string]$InstallScope = $(if ($env:KIWI_CONTROL_INSTALL_SCOPE) { $env:KIWI_CONTROL_INSTALL_SCOPE } else { "user" }),
  [string]$InstallRoot = $(if ($env:KIWI_CONTROL_INSTALL_ROOT) { $env:KIWI_CONTROL_INSTALL_ROOT } else { "" }),
  [string]$PathBin = $(if ($env:KIWI_CONTROL_PATH_BIN) { $env:KIWI_CONTROL_PATH_BIN } else { "" }),
  [string]$ResultPath = $(if ($env:KIWI_CONTROL_RESULT_PATH) { $env:KIWI_CONTROL_RESULT_PATH } else { "" })
)

$ErrorActionPreference = "Stop"
$GlobalHome = if ($InstallScope -eq "machine") {
  if ([string]::IsNullOrWhiteSpace($InstallRoot)) {
    Join-Path $env:ProgramData "Kiwi Control"
  } else {
    $InstallRoot
  }
} else {
  if ($env:KIWI_CONTROL_HOME) { $env:KIWI_CONTROL_HOME } else { Join-Path $HOME ".kiwi-control" }
}
$PathBin = if ([string]::IsNullOrWhiteSpace($PathBin)) { Join-Path $GlobalHome "bin" } else { $PathBin }
$InstallRoot = if ($InstallScope -eq "machine") {
  Join-Path $GlobalHome "cli\kiwi-control-0.2.0-beta.16"
} else {
  Join-Path $GlobalHome "releases\kiwi-control-0.2.0-beta.16"
}
$ReceiptPath = if ([string]::IsNullOrWhiteSpace($ResultPath)) { Join-Path $GlobalHome "desktop-cli-install.json" } else { $ResultPath }

function Remove-KiwiPathEntry([string]$Scope, [string]$TargetPath) {
  $CurrentPath = [Environment]::GetEnvironmentVariable("Path", $Scope)
  if ([string]::IsNullOrWhiteSpace($CurrentPath)) {
    return $false
  }

  $NormalizedTarget = $TargetPath.TrimEnd('\')
  $ExistingEntries = @($CurrentPath -split ';' | Where-Object { -not [string]::IsNullOrWhiteSpace($_) })
  $FilteredEntries = @($ExistingEntries | Where-Object { $_.TrimEnd('\') -ne $NormalizedTarget })
  if ($FilteredEntries.Count -eq $ExistingEntries.Count) {
    return $false
  }

  [Environment]::SetEnvironmentVariable("Path", ($FilteredEntries -join ';'), $Scope)
  return $true
}

$RemovedWrappers = @()
foreach ($CommandName in @("kiwi-control", "kc")) {
  $WrapperPath = Join-Path $PathBin "$CommandName.cmd"
  if (Test-Path $WrapperPath) {
    Remove-Item -Force $WrapperPath
    $RemovedWrappers += $WrapperPath
  }
}

if (Test-Path $InstallRoot) {
  Remove-Item -Recurse -Force $InstallRoot
}

$PathChanged = if ($InstallScope -eq "machine") {
  Remove-KiwiPathEntry "Machine" $PathBin
} else {
  Remove-KiwiPathEntry "User" $PathBin
}

if (Test-Path $ReceiptPath) {
  Remove-Item -Force $ReceiptPath
}

foreach ($Candidate in @($PathBin, (Split-Path -Parent $InstallRoot), $GlobalHome)) {
  if (-not [string]::IsNullOrWhiteSpace($Candidate) -and (Test-Path $Candidate)) {
    try {
      if (-not (Get-ChildItem -Force $Candidate | Select-Object -First 1)) {
        Remove-Item -Force $Candidate
      }
    } catch {
      # Keep cleanup best-effort.
    }
  }
}

if (-not [string]::IsNullOrWhiteSpace($ResultPath)) {
  $payload = @{
    installScope = $InstallScope
    installRoot = $InstallRoot
    installBinDir = $PathBin
    pathChanged = $PathChanged
    removedWrappers = $RemovedWrappers
    updatedAt = (Get-Date).ToString("o")
  } | ConvertTo-Json -Depth 5
  New-Item -ItemType Directory -Force -Path (Split-Path -Parent $ResultPath) | Out-Null
  Set-Content -Path $ResultPath -Value $payload
}
