[CmdletBinding(SupportsShouldProcess = $true, ConfirmImpact = "High")]
param(
    [Parameter(Mandatory = $true)]
    [ValidatePattern("^[0-9a-fA-F]{32}$")]
    [string]$InstallationId,

    [switch]$ConfirmedNoLemonInstance,

    [ValidateScript({ $_ -match "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$" })]
    [string[]]$DeactivatedInstanceId
)

$ErrorActionPreference = "Stop"
Set-StrictMode -Version Latest

$hasDeactivatedInstanceIds = $null -ne $DeactivatedInstanceId -and
    $DeactivatedInstanceId.Length -gt 0
if ([bool]$ConfirmedNoLemonInstance -eq $hasDeactivatedInstanceIds) {
    throw "Specify exactly one proof: -ConfirmedNoLemonInstance, or one or more -DeactivatedInstanceId values."
}

$serviceDirectory = Split-Path -Parent $PSScriptRoot
$configPath = Join-Path $serviceDirectory "wrangler.production.toml"
if (-not (Test-Path -LiteralPath $configPath -PathType Leaf)) {
    throw "The ignored production Wrangler configuration was not found."
}
if (-not (Get-Command pnpm -ErrorAction SilentlyContinue)) {
    throw "pnpm is required to use the pinned Wrangler version."
}

function Invoke-WranglerCapture {
    param([Parameter(Mandatory = $true)][string[]]$Arguments)
    $output = & pnpm exec wrangler @Arguments 2>$null
    if ($LASTEXITCODE -ne 0) { throw "Wrangler could not complete the requested production KV operation." }
    return ($output -join [Environment]::NewLine).Trim()
}

$marker = Invoke-WranglerCapture -Arguments @(
    "kv", "key", "get", "system:namespace-marker:v1",
    "--binding", "LICENSE_STATE", "--remote", "--config", $configPath
)
if ($marker -ne "smartcut64-license-state:production:b48acd15f08540abbdb7026cbdbb0319:v1") {
    throw "The configured production licence-state namespace marker is missing or incorrect."
}

$secureLicenceKey = Read-Host "Customer licence key (input is hidden)" -AsSecureString
$licencePointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureLicenceKey)
try {
    $licenceKey = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($licencePointer).Trim()
    if ($licenceKey.Length -lt 8 -or $licenceKey.Length -gt 256 -or $licenceKey -match "[\x00-\x20\x7f]") {
        throw "The licence key format is invalid."
    }
    $licenceBytes = [Text.Encoding]::UTF8.GetBytes($licenceKey)
    try {
        $licenceHash = [Convert]::ToHexString(
            [Security.Cryptography.SHA256]::HashData($licenceBytes)).ToLowerInvariant()
    }
    finally {
        [Array]::Clear($licenceBytes, 0, $licenceBytes.Length)
    }
}
finally {
    if ($licencePointer -ne [IntPtr]::Zero) {
        [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($licencePointer)
    }
    $licenceKey = $null
    $secureLicenceKey.Dispose()
}

$normalizedInstallationId = $InstallationId.ToLowerInvariant()
$recordKey = "activation:${licenceHash}:${normalizedInstallationId}"
$recordJson = Invoke-WranglerCapture -Arguments @(
    "kv", "key", "get", $recordKey,
    "--binding", "LICENSE_STATE", "--remote", "--config", $configPath
)
try { $record = $recordJson | ConvertFrom-Json }
catch { throw "The production activation record was not valid JSON." }

$hasRecoveryStatus = $record.PSObject.Properties.Name -contains "recovery_status"
$guardedPending = $hasRecoveryStatus -and $record.status -eq "revoked" -and
    $record.recovery_status -eq "activation_pending"
$directPending = -not $hasRecoveryStatus -and $record.status -eq "activation_pending"
if ((-not $guardedPending -and -not $directPending) -or
    $record.installation_id -ne $normalizedInstallationId -or
    -not [string]::IsNullOrEmpty([string]$record.instance_id)) {
    throw "The record is not an unresolved activation_pending record for this installation."
}

$proof = if ($ConfirmedNoLemonInstance) {
    "authoritative_no_matching_instance"
} else {
    "all_matching_instances_deactivated"
}
$record.status = "deactivated"
if ($hasRecoveryStatus) { $record.PSObject.Properties.Remove("recovery_status") }
$record.instance_id = ""
$record.updated_at = [DateTime]::UtcNow.ToString("o")
$record | Add-Member -NotePropertyName recovery_reason -NotePropertyValue $proof -Force
$record | Add-Member -NotePropertyName recovered_instance_ids `
    -NotePropertyValue @($DeactivatedInstanceId | ForEach-Object { $_.ToLowerInvariant() }) -Force
$record | Add-Member -NotePropertyName recovered_at -NotePropertyValue $record.updated_at -Force
$updatedJson = $record | ConvertTo-Json -Depth 12 -Compress

$targetDescription = "production activation_pending record ending $($normalizedInstallationId.Substring(24))"
if (-not $PSCmdlet.ShouldProcess($targetDescription,
    "mark deactivated after authoritative Lemon reconciliation")) {
    return
}

$temporaryPath = [IO.Path]::GetTempFileName()
try {
    [IO.File]::WriteAllText($temporaryPath, $updatedJson, [Text.UTF8Encoding]::new($false))
    & pnpm exec wrangler kv key put $recordKey --path $temporaryPath `
        --binding LICENSE_STATE --remote --config $configPath | Out-Null
    if ($LASTEXITCODE -ne 0) { throw "Wrangler could not update the production activation record." }
}
finally {
    if (Test-Path -LiteralPath $temporaryPath) {
        Remove-Item -LiteralPath $temporaryPath -Force
    }
}

$readbackJson = Invoke-WranglerCapture -Arguments @(
    "kv", "key", "get", $recordKey,
    "--binding", "LICENSE_STATE", "--remote", "--config", $configPath
)
try { $readback = $readbackJson | ConvertFrom-Json }
catch { throw "The updated production activation record could not be verified." }
if ($readback.status -ne "deactivated" -or
    ($readback.PSObject.Properties.Name -contains "recovery_status") -or
    $readback.recovery_reason -ne $proof -or
    $readback.installation_id -ne $normalizedInstallationId) {
    throw "Production activation recovery readback did not match the requested state."
}

Write-Host "Activation recovery completed and verified. The customer may retry activation."
