#Requires -Version 5.1
<#
.SYNOPSIS
  Deploy setup wizard fix, API error exposure, and related static assets to Hetzner.

.EXAMPLE
  cd c:\dev\cnperp-dimensions\deploy\hetzner
  .\Quick-Deploy-SetupPatch.ps1

  # Optional: use ssh-agent instead of the built-in deploy key helper
  .\Quick-Deploy-SetupPatch.ps1 -UseSshAgent
#>
param([switch]$UseSshAgent)

$ErrorActionPreference = "Stop"
$Here = $PSScriptRoot
$RepoRoot = Split-Path (Split-Path $Here -Parent) -Parent
$LocalConfig = Join-Path $Here "production.local.ps1"
if (Test-Path $LocalConfig) { . $LocalConfig }

if (-not $ServerIp) {
    Write-Host "Set ServerIp in production.local.ps1" -ForegroundColor Red
    exit 1
}
$SshUser = if ($SshUser) { $SshUser } else { "root" }
$defaultKey = Join-Path $env:USERPROFILE ".ssh\id_ed25519_cnperp"
$deployKeyTemp = $null

if ($UseSshAgent) {
    $keyForSession = if ($SshKeyPath) { $SshKeyPath } else { $defaultKey }
    Write-Host "Using SSH key via agent: $keyForSession" -ForegroundColor Gray
    $sshArgs = @("-i", $keyForSession, "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=30")
    $scpArgs = @("-i", $keyForSession, "-o", "IdentitiesOnly=yes")
} else {
    # No ssh-agent required — copies key to %TEMP% and strips passphrase (see _prepare-deploy-key.ps1)
    try {
        $deployKeyTemp = (& "$Here\_prepare-deploy-key.ps1" | Select-Object -Last 1).Trim()
        $keyForSession = $deployKeyTemp
        Write-Host "Using prepared deploy key (no ssh-agent)." -ForegroundColor Gray
    } catch {
        Write-Host "Could not prepare deploy key: $_" -ForegroundColor Red
        Write-Host "Update passphrase in _prepare-deploy-key.ps1 or use -UseSshAgent after: ssh-add `"$defaultKey`"" -ForegroundColor Yellow
        exit 1
    }
    $sshArgs = @("-i", $keyForSession, "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=30", "-o", "BatchMode=yes")
    $scpArgs = @("-i", $keyForSession, "-o", "IdentitiesOnly=yes", "-o", "BatchMode=yes")
}

$paths = @(
    "app/main.py",
    "app/core/config.py",
    "app/middleware/api_auth.py",
    "app/api/v1/endpoints/company.py",
    "app/static/company-setup.html",
    "app/static/login.html",
    "app/static/bank-accounts.html",
    "app/static/js/api-error-log.js",
    "app/static/js/cnperp-core.js"
)
foreach ($p in $paths) {
    $full = Join-Path $RepoRoot $p
    if (-not (Test-Path $full)) {
        Write-Host "Missing: $full" -ForegroundColor Red
        exit 1
    }
}

Write-Host "Testing SSH to ${SshUser}@${ServerIp}..." -ForegroundColor Cyan
ssh @sshArgs -o ConnectTimeout=15 "${SshUser}@${ServerIp}" "echo SSH_OK"
if ($LASTEXITCODE -ne 0) {
    if ($UseSshAgent) {
        Write-Host "SSH failed. Start agent and run: ssh-add `"$defaultKey`"" -ForegroundColor Red
    } else {
        Write-Host "SSH failed. Check ServerIp and _prepare-deploy-key.ps1 passphrase." -ForegroundColor Red
    }
    exit 1
}

$archive = Join-Path $env:TEMP "cnperp-setup-patch.tar.gz"
if (Test-Path $archive) { Remove-Item -Force $archive }
$tarArgs = @("-czf", $archive, "-C", $RepoRoot)
foreach ($p in $paths) { $tarArgs += $p }
& tar @tarArgs
if ($LASTEXITCODE -ne 0) { Write-Host "tar failed" -ForegroundColor Red; exit 1 }

Write-Host "Uploading patch ($([math]::Round((Get-Item $archive).Length/1KB)) KB)..." -ForegroundColor Cyan
scp @scpArgs $archive "${SshUser}@${ServerIp}:/tmp/cnperp-setup-patch.tar.gz"
if ($LASTEXITCODE -ne 0) { exit 1 }

$remote = @'
set -e
cd /opt/cnperp
tar -xzf /tmp/cnperp-setup-patch.tar.gz
chown -R cnperp:cnperp app/main.py app/core/config.py app/middleware/api_auth.py \
  app/api/v1/endpoints/company.py app/static/company-setup.html app/static/login.html \
  app/static/bank-accounts.html app/static/js/api-error-log.js app/static/js/cnperp-core.js
systemctl restart cnperp
sleep 2
systemctl is-active cnperp
curl -sf http://127.0.0.1:8000/health || true
echo PATCH_OK
'@ -replace "`r", ""

Write-Host "Applying on server and restarting cnperp..." -ForegroundColor Cyan
ssh @sshArgs "${SshUser}@${ServerIp}" $remote
if ($LASTEXITCODE -ne 0) {
    Write-Host "Remote apply failed." -ForegroundColor Red
    exit 1
}

if ($deployKeyTemp) {
    Remove-Item -Force $deployKeyTemp, "$deployKeyTemp.pub" -ErrorAction SilentlyContinue
}

Write-Host "`nDeployed. Verify:" -ForegroundColor Green
Write-Host "  Setup:  https://erp.cnpsolutions.co.bw/setup  (Ctrl+Shift+R to hard-refresh)" -ForegroundColor Green
Write-Host "  Health: https://erp.cnpsolutions.co.bw/health" -ForegroundColor Green
