# Reset PLATFORM_ADMIN_SECRET on Hetzner (fixes God Mode 403 wrong password).
#Requires -Version 5.1
$ErrorActionPreference = "Stop"
. (Join-Path $PSScriptRoot "production.local.ps1")

$sshArgs = @("-o", "ServerAliveInterval=30")
if ($SshKeyPath -and (Test-Path $SshKeyPath)) {
    $sshArgs = @("-i", $SshKeyPath, "-o", "IdentitiesOnly=yes") + $sshArgs
}

$custom = Read-Host "Enter new God Mode secret (or press Enter to auto-generate)"
if (-not $custom) { $custom = "" }

$script = Join-Path $PSScriptRoot "reset-platform-secret.sh"
scp @sshArgs $script "root@${ServerIp}:/tmp/reset-platform-secret.sh"
if ($custom) {
    $escaped = $custom -replace "'", "'\''"
    $out = ssh @sshArgs "root@$ServerIp" "sed -i 's/\r$//' /tmp/reset-platform-secret.sh; chmod +x /tmp/reset-platform-secret.sh; bash /tmp/reset-platform-secret.sh /opt/cnperp/.env '$escaped'" 2>&1
} else {
    $out = ssh @sshArgs "root@$ServerIp" "sed -i 's/\r$//' /tmp/reset-platform-secret.sh; chmod +x /tmp/reset-platform-secret.sh; bash /tmp/reset-platform-secret.sh" 2>&1
}
$out | ForEach-Object { Write-Host $_ }

$secretLine = ($out | Where-Object { $_ -match '^\s*Secret:\s+' }) -replace '^\s*Secret:\s+', ''
if ($secretLine) {
    $secret = $secretLine.Trim()
    $localPs1 = Join-Path $PSScriptRoot "production.local.ps1"
    if (Test-Path $localPs1) {
        $content = Get-Content $localPs1 -Raw
        if ($content -match '(?m)^\$LicenseAdminSecret\s*=') {
            $content = $content -replace '(?m)^\$LicenseAdminSecret\s*=.*', "`$LicenseAdminSecret = `"$secret`""
        } else {
            $content = $content.TrimEnd() + "`n`$LicenseAdminSecret = `"$secret`"`n"
        }
        Set-Content -Path $localPs1 -Value $content -NoNewline
        Write-Host "`nSaved to production.local.ps1 (future deploys keep this code)." -ForegroundColor Green
    }
    Write-Host "`n*** SAVE THIS ACCESS CODE ***" -ForegroundColor Yellow
    Write-Host $secret
}

Write-Host "`nLogin: https://$Domain/platform-admin" -ForegroundColor Green
Write-Host "Tip: You do not need to deploy again — only reset if you want a new code." -ForegroundColor Gray
