"""kubeseal HybridEncrypt: namespace-wide sealing (matches backend/src/deploy/kubeseal.ts sealValueNamespaceWide).

Format: base64( uint16be(len(rsa)) || rsa || aes )
- rsa = RSA-OAEP(SHA-256, label=namespace) of a 32-byte session key
- aes = AES-256-GCM(zero-nonce, plaintext) → ciphertext || 16-byte tag
"""
import base64
import os

from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.x509 import load_pem_x509_certificate

# Нулевой nonce каноничен для kubeseal: session key одноразовый, переиспользования пары ключ+nonce нет.
_ZERO_NONCE = b"\x00" * 12


def seal_namespace_wide(cert_pem: str, namespace: str, value: str) -> str:
    """Seal value so it decrypts under any secret name in namespace (kubeseal namespace-wide scope).

    Raise ValueError if the cert PEM is not a valid RSA certificate.
    """
    try:
        pub = load_pem_x509_certificate(cert_pem.encode()).public_key()
    except Exception as exc:
        raise ValueError(f"invalid sealed-secrets cert: {exc}") from exc

    session_key = os.urandom(32)
    rsa_block = pub.encrypt(
        session_key,
        padding.OAEP(
            mgf=padding.MGF1(hashes.SHA256()),
            algorithm=hashes.SHA256(),
            label=namespace.encode(),
        ),
    )
    # AESGCM.encrypt returns ciphertext || 16-byte tag — same as Node cipher.final()+getAuthTag().
    aes_block = AESGCM(session_key).encrypt(_ZERO_NONCE, value.encode(), None)
    return base64.b64encode(len(rsa_block).to_bytes(2, "big") + rsa_block + aes_block).decode()
