"""PKCS#12 (.p12/.pfx) loading helpers."""

from __future__ import annotations

import datetime as _dt
from dataclasses import dataclass
from typing import Optional, Sequence

from cryptography import x509
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.primitives.serialization import pkcs12


@dataclass(frozen=True)
class Pkcs12Material:
    """In-memory representation of a PKCS#12 container."""

    private_key: RSAPrivateKey
    certificate: x509.Certificate
    additional_certificates: Sequence[x509.Certificate]

    @property
    def not_valid_after(self) -> _dt.datetime:
        """Certificate expiration datetime."""

        return self.certificate.not_valid_after


def load_pkcs12(pfx_bytes: bytes, password: Optional[str]) -> Pkcs12Material:
    """Load PKCS#12 data and return key/certificate material.

    Args:
        pfx_bytes: Raw bytes of the PKCS#12 file (.p12/.pfx).
        password: Password as string or None.

    Returns:
        Pkcs12Material with private key and certificate.

    Raises:
        ValueError: if the container cannot be parsed.
    """

    pwd = password.encode("utf-8") if password is not None else None
    key, cert, additional = pkcs12.load_key_and_certificates(pfx_bytes, pwd)
    if key is None or cert is None:
        raise ValueError("El PKCS#12 no contiene clave privada y/o certificado")

    if not isinstance(key, RSAPrivateKey):
        raise ValueError("Solo se soporta RSA private key para XMLDSig (rsa-sha256)")

    return Pkcs12Material(private_key=key, certificate=cert, additional_certificates=additional or ())
