#Requires -RunAsAdministrator
$ErrorActionPreference = "SilentlyContinue"
$Host.UI.RawUI.WindowTitle = "Stop Claude Proxy Control"
try { chcp 65001 | Out-Null; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false) } catch {}
. (Join-Path $PSScriptRoot "_env.ps1")

Write-Host ""
Write-Host "============================================================" -ForegroundColor White
Write-Host "  Stop Claude Proxy Control (product)" -ForegroundColor Yellow
Write-Host "============================================================" -ForegroundColor White
Write-Host ("  Home: " + $ProductHome) -ForegroundColor DarkGray

$statusPath = Join-Path $MergedDir "status.json"
$tunName = $null
if (Test-Path $statusPath) {
  try {
    $st = Get-Content $statusPath -Raw | ConvertFrom-Json
    if ($st.tun) { $tunName = [string]$st.tun }
  } catch {}
}

Write-Host ""
Write-Host "==> BEFORE" -ForegroundColor Cyan
$ours = @(Get-CpcSingBoxProcesses)
$other = @(Get-OtherSingBoxProcesses)
Write-Host ("  CPC sing-box: {0}" -f $ours.Count)
Write-Host ("  other sing-box (не трогаем): {0}" -f $other.Count)

Write-Host ""
Write-Host "==> Stop CPC sing-box / TUN" -ForegroundColor Cyan
[void](Stop-CpcSingBox)
Start-Sleep -Seconds 2

if ($tunName) {
  Get-NetAdapter -Name $tunName -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Host ("  disable adapter {0}" -f $_.Name) -ForegroundColor Yellow
    Disable-NetAdapter -Name $_.Name -Confirm:$false -ErrorAction SilentlyContinue
  }
}

Write-Host ""
Write-Host "==> Close Claude" -ForegroundColor Cyan
foreach ($name in @("Claude", "claude", "cowork-svc")) {
  Get-Process -Name $name -ErrorAction SilentlyContinue | ForEach-Object {
    Write-Host ("  stop {0} pid={1}" -f $name, $_.Id) -ForegroundColor Yellow
    Stop-Process -Id $_.Id -Force -ErrorAction SilentlyContinue
  }
}

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

Write-Host ""
Write-Host "Done. CPC tunnel OFF. Личный ~/.claude-proxy не трогали." -ForegroundColor Green
if (-not $env:CLAUDE_PROXY_NOPAUSE) {
  Write-Host "Enter..." -ForegroundColor DarkGray
  [void][Console]::ReadLine()
}
