"""Load and manage encryption keys."""
from __future__ import annotations

import logging
import os

logger = logging.getLogger("fibinaci.encryption")

_cached_key: bytes | None = None


def load_public_key(path: str | None = None) -> bytes | None:
    """Load the RSA public key from FIBINACI_ENCRYPTION_KEY_PATH."""
    global _cached_key
    if _cached_key is not None:
        return _cached_key

    key_path = path or os.environ.get("FIBINACI_ENCRYPTION_KEY_PATH")
    if not key_path:
        return None

    try:
        with open(key_path, "rb") as f:
            _cached_key = f.read()
        logger.info("Loaded encryption key from %s", key_path)
        return _cached_key
    except Exception:
        logger.warning("Failed to load encryption key from %s", key_path, exc_info=True)
        return None


def clear_cached_key() -> None:
    global _cached_key
    _cached_key = None
