"""Managed API key generation and validation utilities.

Supports multi-API-key management for insurance agent customers
who need more than one API key to integrate with multiple services.

Key format:
    Legacy:  lls_<40 hex chars>
    Managed: lls_mk_<40 hex chars>
"""

import hashlib
import secrets

MIN_EXPIRATION_DAYS = 1
MAX_EXPIRATION_DAYS = 730

MANAGED_KEY_PREFIX = "lls_mk_"
KEY_ID_PREFIX = "mk_"


def generate_key_id() -> str:
    """Generate a unique key ID with mk_ prefix.

    Returns a key ID in the format ``mk_<24 hex chars>`` using 96-bit
    entropy via :func:`secrets.token_hex`.
    """
    return f"{KEY_ID_PREFIX}{secrets.token_hex(12)}"


def generate_managed_key() -> str:
    """Generate a new managed API key.

    Returns a key in the format ``lls_mk_<40 hex chars>`` using 160-bit
    entropy via :func:`secrets.token_hex`.
    """
    return f"{MANAGED_KEY_PREFIX}{secrets.token_hex(20)}"


def compute_key_hash(key: str) -> str:
    """Compute the SHA-256 hash of an API key.

    Args:
        key: The full API key string.

    Returns:
        Hex digest of the SHA-256 hash.
    """
    return hashlib.sha256(key.encode()).hexdigest()


def validate_expiration_days(days: int) -> bool:
    """Validate that an expiration period is within the allowed range.

    Args:
        days: Number of days until key expiration.

    Returns:
        ``True`` if *days* is between 1 and 730 inclusive, ``False`` otherwise.
    """
    return MIN_EXPIRATION_DAYS <= days <= MAX_EXPIRATION_DAYS
