[CmdletBinding()]
param(
    [string]$InstallRoot = (Join-Path $env:LOCALAPPDATA "Programs\BMCLI"),
    [switch]$KeepAI
)

$ErrorActionPreference = "Stop"
$InstallRoot = [IO.Path]::GetFullPath($InstallRoot)
$binRoot = Join-Path $InstallRoot "bin"
$binary = Join-Path $binRoot "bmcli.exe"
if (Test-Path -LiteralPath $binary -PathType Leaf) {
    try {
        & $binary daemon stop 2>$null | Out-Null
    } catch {
        # Continue uninstalling a damaged or already-stopped installation.
    }
}
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
$parts = @($currentPath.Split(';') | Where-Object { $_ -ne $binRoot })
[Environment]::SetEnvironmentVariable("Path", ($parts -join ';'), "User")

if (-not $KeepAI) {
    $agentsRoot = if ($env:AGENTS_HOME) { $env:AGENTS_HOME } else { Join-Path $HOME ".agents" }
    $claudeRoot = if ($env:CLAUDE_CONFIG_DIR) { $env:CLAUDE_CONFIG_DIR } else { Join-Path $HOME ".claude" }
    foreach ($skill in @(
        (Join-Path $agentsRoot "skills\bmcli"),
        (Join-Path $claudeRoot "skills\bmcli")
    )) {
        Remove-Item -LiteralPath $skill -Recurse -Force -ErrorAction SilentlyContinue
    }
}

Remove-Item -LiteralPath $InstallRoot -Recurse -Force -ErrorAction SilentlyContinue
Write-Output "BMCLI was removed. Open a new terminal to refresh PATH."
