#Requires -Version 5.1
<#
.SYNOPSIS
  Deploy licensing + God Mode + setup wizard patches to production (small upload, ~30s).

.PREREQUISITES
  production.local.ps1 with ServerIp and SshKeyPath.
  Load SSH key once:  ssh-add $env:USERPROFILE\.ssh\id_ed25519_cnperp

.EXAMPLE
  cd deploy\hetzner
  ssh-add $env:USERPROFILE\.ssh\id_ed25519_cnperp
  .\Quick-Deploy-GodModePatch.ps1
#>
$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" }
$SshKeyPath = if ($SshKeyPath) { $SshKeyPath } else { Join-Path $env:USERPROFILE ".ssh\id_ed25519_cnperp" }
$sshArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes", "-o", "ServerAliveInterval=30")
$scpArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes")

$paths = @(
    "app/core/config.py",
    "app/core/platform_admin.py",
    "app/schemas/licensing.py",
    "app/services/licensing_service.py",
    "app/api/v1/endpoints/platform_admin.py",
    "app/schemas/platform_admin.py",
    "app/services/platform_admin_service.py",
    "app/static/platform-admin.html",
    "app/static/company-setup.html",
    "deploy/hetzner/bootstrap-production.sh"
)
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) {
    Write-Host "SSH failed. Run: ssh-add `"$SshKeyPath`"" -ForegroundColor Red
    exit 1
}

$archive = Join-Path $env:TEMP "cnperp-godmode-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-godmode-patch.tar.gz"
if ($LASTEXITCODE -ne 0) { exit 1 }

$remote = @'
set -e
cd /opt/cnperp
tar -xzf /tmp/cnperp-godmode-patch.tar.gz
chown -R cnperp:cnperp app/core/config.py app/core/platform_admin.py \
  app/schemas/licensing.py app/schemas/platform_admin.py \
  app/services/licensing_service.py app/services/platform_admin_service.py \
  app/api/v1/endpoints/platform_admin.py app/schemas/platform_admin.py \
  app/static/platform-admin.html app/static/company-setup.html deploy/hetzner/bootstrap-production.sh
grep -q '^PLATFORM_ADMIN_TOKEN_HOURS=' /opt/cnperp/.env && \
  sed -i 's/^PLATFORM_ADMIN_TOKEN_HOURS=.*/PLATFORM_ADMIN_TOKEN_HOURS=0/' /opt/cnperp/.env || \
  echo 'PLATFORM_ADMIN_TOKEN_HOURS=0' >> /opt/cnperp/.env
systemctl restart cnperp
sleep 2
systemctl is-active cnperp
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
}

Write-Host "`nDeployed. Verify:" -ForegroundColor Green
Write-Host "  God Mode:  https://erp.cnpsolutions.co.bw/platform-admin" -ForegroundColor Green
Write-Host "  Setup:     https://erp.cnpsolutions.co.bw/setup" -ForegroundColor Green
