#Requires -RunAsAdministrator
# Silent stop for "Close program" button: TUN off + Claude closed, no Pause.
$ErrorActionPreference = "SilentlyContinue"
$env:CLAUDE_PROXY_NOPAUSE = "1"
. (Join-Path $PSScriptRoot "_env.ps1")

$statusPath = Join-Path $MergedDir "status.json"
$tunName = $null
if (Test-Path $statusPath) {
  try {
    $raw = Get-Content $statusPath -Raw -Encoding UTF8
    if ($raw.Length -gt 0 -and [int][char]$raw[0] -eq 0xFEFF) { $raw = $raw.Substring(1) }
    $st = $raw | ConvertFrom-Json
    if ($st.tun) { $tunName = [string]$st.tun }
  } catch {}
}

[void](Stop-CpcSingBox)
Start-Sleep -Seconds 1

if ($tunName) {
  Disable-NetAdapter -Name $tunName -Confirm:$false -ErrorAction SilentlyContinue
}
Get-NetAdapter -Name "cpc*" -ErrorAction SilentlyContinue | ForEach-Object {
  if ($_.Status -eq "Up") {
    Disable-NetAdapter -Name $_.Name -Confirm:$false -ErrorAction SilentlyContinue
  }
}

# Close Claude Desktop hard — must not stay online after CPC quit/restart
foreach ($name in @("Claude", "claude", "cowork-svc")) {
  try { & taskkill.exe /IM "$name.exe" /F /T 2>$null | Out-Null } catch {}
  Get-Process -Name $name -ErrorAction SilentlyContinue | ForEach-Object {
    Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
  }
}
Get-Process -ErrorAction SilentlyContinue | Where-Object {
  $_.ProcessName -match '^(?i)(Claude|cowork-svc)$' -or
  ($_.Path -and $_.Path -match '(?i)AnthropicClaude|\\Claude\\')
} | ForEach-Object {
  Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
}

@{
  ok = $true
  stopped = $true
  product = "cpc"
  quit = $true
  time = (Get-Date).ToString("o")
  singBox = @(Get-CpcSingBoxProcesses).Count
  claude = @(Get-Process -Name Claude,claude -ErrorAction SilentlyContinue).Count
} | ConvertTo-Json | Set-Content $statusPath -Encoding UTF8

exit 0
