param(
    [string]$SecretBase64,
    [string]$SecretYamlPath = "deploy/k8s/secrets/jwt-secret.yaml",
    [string]$Kid = "juwan-hs256-1",
    [string]$Issuer = "juwan-user-rpc"
)

function Convert-ToBase64Url {
    param([byte[]]$Bytes)

    $base64 = [Convert]::ToBase64String($Bytes)
    return $base64.TrimEnd('=').Replace('+', '-').Replace('/', '_')
}

function Get-SecretBase64FromYaml {
    param([string]$Path)

    if (-not (Test-Path -Path $Path)) {
        throw "Secret yaml not found: $Path"
    }

    $content = Get-Content -Path $Path -Raw -Encoding UTF8
    $match = [regex]::Match($content, '(?m)^\s*secret-key\s*:\s*([A-Za-z0-9+/=]+)\s*$')
    if (-not $match.Success) {
        throw "Cannot find data.secret-key in: $Path"
    }

    return $match.Groups[1].Value
}

if ([string]::IsNullOrWhiteSpace($SecretBase64)) {
    $SecretBase64 = Get-SecretBase64FromYaml -Path $SecretYamlPath
}

try {
    $rawSecret = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($SecretBase64))
}
catch {
    throw "Invalid base64 secret value. Error: $($_.Exception.Message)"
}

$kBytes = [Text.Encoding]::UTF8.GetBytes($rawSecret)
$kBase64Url = Convert-ToBase64Url -Bytes $kBytes

$jwkObject = @{
    keys = @(
        @{
            kty = "oct"
            k   = $kBase64Url
            alg = "HS256"
            use = "sig"
            kid = $Kid
        }
    )
}

$jwkJson = $jwkObject | ConvertTo-Json -Compress

Write-Output "=== INPUT ==="
Write-Output "secret(base64): $SecretBase64"
Write-Output "secret(raw):    $rawSecret"
Write-Output ""
Write-Output "=== JWK inline_string ==="
Write-Output $jwkJson
Write-Output ""
Write-Output "=== Envoy jwt_authn snippet ==="
Write-Output ('issuer: "{0}"' -f $Issuer)
Write-Output "local_jwks:"
Write-Output ('  inline_string: ''{0}''' -f $jwkJson)
