"""API Key authentication provider."""

import logging
import hashlib
import hmac
from typing import Dict, Any
from .models import AuthenticationError

LOGGER = logging.getLogger(__name__)


class APIKeyAuthProvider:
    """Authenticate requests using API keys."""
    
    def __init__(self, keys: Dict[str, Dict[str, Any]]):
        """Initialize API key auth provider.
        
        Args:
            keys: Dictionary mapping key hashes to metadata
                  Format: {"key_hash": {"name": "...", "scopes": [...], "id": "..."}}
        """
        self.keys = keys
        LOGGER.info(
            "Initialized API key auth provider",
            extra={"context": {"num_keys": len(keys)}},
        )
    
    async def authenticate(self, token: str) -> Dict[str, Any]:
        """Validate API key against stored hashes.
        
        Args:
            token: API key string
            
        Returns:
            User context dictionary
            
        Raises:
            AuthenticationError: If API key is invalid
        """
        # Hash the incoming key
        key_hash = self._hash_key(token)
        
        # Look up key metadata
        key_metadata = self.keys.get(key_hash)
        if not key_metadata:
            LOGGER.warning("Invalid API key attempt")
            raise AuthenticationError("Invalid API key")
        
        # Verify the key hasn't been revoked
        if key_metadata.get("revoked", False):
            LOGGER.warning(
                "Revoked API key used",
                extra={"context": {"key_id": key_metadata.get("id")}},
            )
            raise AuthenticationError("API key has been revoked")
        
        # Build user context
        user_context = {
            "id": key_metadata.get("id", key_hash[:16]),
            "email": None,
            "name": key_metadata.get("name", "API Key User"),
            "roles": key_metadata.get("roles", []),
            "scopes": key_metadata.get("scopes", []),
            "tenant_id": None,
            "source": "api_key",
        }
        
        LOGGER.debug(
            "Successfully authenticated API key",
            extra={"context": {"key_name": user_context["name"]}},
        )
        
        return user_context
    
    @staticmethod
    def _hash_key(key: str) -> str:
        """Generate SHA-256 hash of API key.
        
        Args:
            key: Plain text API key
            
        Returns:
            Hexadecimal hash string
        """
        return hashlib.sha256(key.encode("utf-8")).hexdigest()
    
    @staticmethod
    def generate_key() -> str:
        """Generate a new random API key.
        
        Returns:
            Random API key string (base64-encoded)
        """
        import secrets
        return secrets.token_urlsafe(32)
