"""API key verification service.

AUTO-GENERATED BY PRISM - DO NOT EDIT
Simple API key authentication for backend services.
"""

from __future__ import annotations

import os


class APIKeyError(Exception):
    """API key validation error."""

    pass


class APIKeyService:
    """Service for verifying API keys against environment variable."""

    def __init__(self) -> None:
        """Initialize API key service."""
        self._env_var = "{{ env_var }}"
        self._allow_multiple = {{ allow_multiple_keys }}
        self._valid_keys: set[str] | None = None

    def _load_keys(self) -> set[str]:
        """Load valid API keys from environment variable.

        Returns:
            Set of valid API keys

        Raises:
            APIKeyError: If environment variable is not set
        """
        if self._valid_keys is not None:
            return self._valid_keys

        raw_keys = os.environ.get(self._env_var)
        if not raw_keys:
            raise APIKeyError(f"Environment variable {self._env_var} is not set")

        if self._allow_multiple:
            # Split by comma and strip whitespace
            self._valid_keys = {k.strip() for k in raw_keys.split(",") if k.strip()}
        else:
            self._valid_keys = {raw_keys.strip()}

        if not self._valid_keys:
            raise APIKeyError(f"No valid API keys found in {self._env_var}")

        return self._valid_keys

    def verify_key(self, api_key: str) -> bool:
        """Verify an API key.

        Args:
            api_key: The API key to verify

        Returns:
            True if valid, False otherwise
        """
        try:
            valid_keys = self._load_keys()
            return api_key in valid_keys
        except APIKeyError:
            return False

    def require_key(self, api_key: str) -> None:
        """Require a valid API key, raising an exception if invalid.

        Args:
            api_key: The API key to verify

        Raises:
            APIKeyError: If the API key is invalid or env var not set
        """
        valid_keys = self._load_keys()
        if api_key not in valid_keys:
            raise APIKeyError("Invalid API key")

    def reload_keys(self) -> None:
        """Force reload of API keys from environment variable.

        Useful when keys are rotated without restarting the application.
        """
        self._valid_keys = None
        self._load_keys()


# Singleton instance
api_key_service = APIKeyService()
