#Requires -RunAsAdministrator
<#
  One-time cleanup on this PC:
  - remove PERSONAL ClaudeProxy-* tasks
  - install PRODUCT CPC runtime only
  - leave one desktop shortcut
#>
$ErrorActionPreference = "Continue"
try { chcp 65001 | Out-Null } catch {}

$ProductHome = Join-Path $env:USERPROFILE ".claude-proxy-control"
$RuntimeSrc = Join-Path $env:USERPROFILE ".claude-proxy\product\runtime"
$DesktopSrc = Join-Path $env:USERPROFILE ".claude-proxy\product\desktop"
$Desk = [Environment]::GetFolderPath("Desktop")
$Archive = Join-Path $Desk "_old_claude_shortcuts"

$Log = Join-Path $env:USERPROFILE ".claude-proxy-control\cleanup-last.log"
function Log([string]$m) {
  $line = "$(Get-Date -Format o) $m"
  Add-Content -Path $Log -Value $line -Encoding UTF8
  Write-Host $m
}
New-Item -ItemType Directory -Force -Path (Split-Path $Log) | Out-Null
"" | Set-Content $Log -Encoding UTF8
Log "START cleanup product-only"

# 1) Stop/remove personal tasks
foreach ($t in @("ClaudeProxy-SotaCaptureWatcher", "ClaudeProxy-NetMonitor")) {
  Write-Host ("Remove task: " + $t) -ForegroundColor Yellow
  Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
}

# Kill personal watcher processes
Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue |
  Where-Object {
    $_.CommandLine -match 'Watch-SotaCapture\.ps1' -and
    $_.CommandLine -match '\\.claude-proxy\\' -and
    $_.CommandLine -notmatch 'claude-proxy-control'
  } |
  ForEach-Object {
    Write-Host ("  kill personal watcher pid=" + $_.ProcessId)
    Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
  }

# Kill ONLY product/personal sing-box (never guess Sota if path empty under Program Files)
Get-CimInstance Win32_Process -Filter "Name='sing-box.exe'" -ErrorAction SilentlyContinue | ForEach-Object {
  $p = [string]$_.ExecutablePath
  if ($p -and ($p -like "*\.claude-proxy\sing-box*" -or $p -like "*\.claude-proxy-control\sing-box*")) {
    Write-Host ("  stop our sing-box pid=" + $_.ProcessId + " " + $p) -ForegroundColor Yellow
    Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue
  }
}

# 2) Install product runtime (reuse Install-Product.ps1)
$env:CLAUDE_PROXY_NOPAUSE = "1"
$install = Join-Path $RuntimeSrc "Install-Product.ps1"
if (-not (Test-Path $install)) { throw "Missing $install" }
Write-Host "Running Install-Product.ps1 ..." -ForegroundColor Cyan
& $install

# 3) Archive confusing desktop shortcuts; keep one product launcher
New-Item -ItemType Directory -Force -Path $Archive | Out-Null
$keepNames = @(
  "Claude Proxy Control.lnk"
)
$movePatterns = @(
  "Claude + VPN.bat",
  "Claude + VPN.lnk",
  "Claude Proxy Control (safe).lnk",
  "Claude Proxy Control v2.bat",
  "Diagnose Claude + VPN.bat",
  "Stop Claude + VPN.bat",
  "Stop Claude + VPN.lnk",
  "Stop Claude Proxy TUN.bat",
  "Watch Claude Network.bat",
  "Claude Code via Proxy.bat",
  "Claude via Proxy.bat"
)
foreach ($name in $movePatterns) {
  $src = Join-Path $Desk $name
  if (Test-Path $src) {
    Move-Item $src (Join-Path $Archive $name) -Force
    Write-Host ("  archived: " + $name) -ForegroundColor DarkGray
  }
}

# Recreate the single product shortcut
$bat = Join-Path $DesktopSrc "Run-Product.bat"
$lnkPath = Join-Path $Desk "Claude Proxy Control.lnk"
$w = New-Object -ComObject WScript.Shell
$lnk = $w.CreateShortcut($lnkPath)
$lnk.TargetPath = $bat
$lnk.WorkingDirectory = $DesktopSrc
$lnk.WindowStyle = 7
$ico = Join-Path $DesktopSrc "claude-proxy-control.ico"
if (Test-Path $ico) { $lnk.IconLocation = $ico }
$lnk.Description = "Claude Proxy Control — product (client)"
$lnk.Save()
Write-Host ("Shortcut OK: " + $lnkPath) -ForegroundColor Green

# Marker: personal GUI should not be used
$note = Join-Path $env:USERPROFILE ".claude-proxy\USE_PRODUCT_ONLY.txt"
@"
На этом ПК используем только PRODUCT:
  %USERPROFILE%\.claude-proxy-control
  ярлык: Claude Proxy Control.lnk
  запуск: product\desktop\Run-Product.bat

Личные задачи ClaudeProxy-* сняты.
Старые ярлыки на рабочем столе: _old_claude_shortcuts\
"@ | Set-Content $note -Encoding UTF8

Log "DONE cleanup product-only"
Write-Host ""
Write-Host "DONE. Дальше как клиент:" -ForegroundColor Green
Write-Host "  1) В Sota: Disconnect (если Connect включён)"
Write-Host "  2) Ярлык Claude Proxy Control → ключ уже есть"
Write-Host "  3) Ловец → Sota Connect/Disconnect → Старт"
Write-Host ""
if (-not $env:CLAUDE_PROXY_NOPAUSE) { Pause }
