"""Authentication middleware to resolve email from API tokens or headers."""

from typing import Optional
from starlette.requests import Request
from agenticlypay.utils.firestore_storage import FirestoreStorage

storage = FirestoreStorage()


def resolve_email_from_auth(request: Request) -> Optional[str]:
    """Resolve developer email from request authentication.
    
    Checks in order:
    1. Authorization: Bearer <token> header (API token)
    2. X-Developer-Email header
    3. email query parameter
    
    Args:
        request: Starlette request object
        
    Returns:
        Developer email address if found, None otherwise
    """
    # Check for API token in Authorization header
    auth_header = request.headers.get("Authorization", "")
    if auth_header.startswith("Bearer "):
        token = auth_header[7:].strip()  # Remove "Bearer " prefix
        if token:
            token_info = storage.verify_api_token(token)
            if token_info and token_info.get("is_active"):
                return token_info.get("email")
    
    # Fallback to X-Developer-Email header
    email = request.headers.get("X-Developer-Email")
    if email:
        return email
    
    # Fallback to email query parameter
    email = request.query_params.get("email")
    if email:
        return email
    
    return None

