# Run rembg-local.py with SSH tunnel
# Usage: powershell -File run-rembg.ps1 [-Batch 500] [-Priority p1]

param(
    [int]$Batch = 500,
    [string]$Priority = "all",
    [float]$Delay = 0.5
)

$ErrorActionPreference = "Continue"
$VPS_KEY = "$env:USERPROFILE\.ssh\hostinger_vps"
$SCRIPT_DIR = Split-Path -Parent $MyInvocation.MyCommand.Path

Write-Host "=== SneakerPicks Rembg Runner ===" -ForegroundColor Cyan
Write-Host "  Batch: $Batch | Priority: $Priority | Delay: $Delay"

# Kill any existing SSH tunnels on port 5433
$existing = Get-Process ssh -ErrorAction SilentlyContinue
if ($existing) {
    Write-Host "  Cleaning up existing SSH processes..."
    Stop-Process -Name ssh -Force -ErrorAction SilentlyContinue
    Start-Sleep 2
}

# Start SSH tunnel
Write-Host "  Starting SSH tunnel on port 5433..."
$tunnel = Start-Process -FilePath "ssh" -ArgumentList @(
    "-i", $VPS_KEY,
    "-L", "5433:172.18.0.5:5432",
    "-N",
    "-o", "StrictHostKeyChecking=no",
    "-o", "ServerAliveInterval=60",
    "root@72.62.45.83"
) -PassThru -WindowStyle Hidden

Start-Sleep 3

# Check tunnel
$test = Test-NetConnection localhost -Port 5433 -WarningAction SilentlyContinue
if (-not $test.TcpTestSucceeded) {
    Write-Host "  ERROR: SSH tunnel failed to start!" -ForegroundColor Red
    if ($tunnel -and !$tunnel.HasExited) { Stop-Process -Id $tunnel.Id -Force }
    exit 1
}
Write-Host "  SSH tunnel active (PID: $($tunnel.Id))" -ForegroundColor Green

# Run rembg
Write-Host "  Starting rembg processing..."
try {
    & python "$SCRIPT_DIR\rembg-local.py" --batch $Batch --priority $Priority --delay $Delay
} finally {
    # Cleanup tunnel
    Write-Host "`n  Cleaning up SSH tunnel..."
    if ($tunnel -and !$tunnel.HasExited) {
        Stop-Process -Id $tunnel.Id -Force
    }
}

Write-Host "=== Done ===" -ForegroundColor Cyan
