import logging
from soagila.core.encryption.simulated_he import get_encryption_engine

logger = logging.getLogger("soagila.airlock.keys")

# Cache for org and user keys to avoid regenerating
_org_keys: dict[str, str] = {}    # org_id -> key_ref
_user_keys: dict[str, str] = {}   # user_id -> key_ref


def get_or_create_org_key(org_id: str) -> str:
    """Get or create organization master key."""
    if org_id in _org_keys:
        engine = get_encryption_engine()
        if engine.key_exists(_org_keys[org_id]):
            return _org_keys[org_id]

    engine = get_encryption_engine()
    key_ref = engine.generate_key("org_master")
    _org_keys[org_id] = key_ref
    logger.info(f"Created org master key for org {org_id}: {key_ref}")
    return key_ref


def get_or_create_user_mek(user_id: str) -> str:
    """Get or create user Memory Encryption Key (MEK)."""
    if user_id in _user_keys:
        engine = get_encryption_engine()
        if engine.key_exists(_user_keys[user_id]):
            return _user_keys[user_id]

    engine = get_encryption_engine()
    key_ref = engine.generate_key("user_mek")
    _user_keys[user_id] = key_ref
    logger.info(f"Created user MEK for user {user_id}: {key_ref}")
    return key_ref


def create_session_key(session_id: str) -> str:
    """Create an ephemeral session key."""
    engine = get_encryption_engine()
    key_ref = engine.generate_key("session")
    logger.debug(f"Created session key for session {session_id}: {key_ref}")
    return key_ref


def destroy_user_keys(user_id: str) -> bool:
    """Destroy all keys for a user (cryptographic annihilation)."""
    engine = get_encryption_engine()
    destroyed = False

    if user_id in _user_keys:
        destroyed = engine.destroy_key(_user_keys[user_id])
        del _user_keys[user_id]
        logger.info(f"Annihilated user MEK for user {user_id}")

    return destroyed
