from fastapi import Header
from typing import Optional, Dict
from ..exceptions.base import AuthenticationException
import structlog

logger = structlog.get_logger("auth_middleware")


class ServiceAuthManager:
    """Manages authentication for services"""

    def __init__(self, global_token: str, service_tokens: Dict[str, Optional[str]]):
        self.global_token = global_token
        self.service_tokens = service_tokens or {}

    def verify_service_token(self, service_name: str, authorization: Optional[str]) -> bool:
        """Verify bearer token for specific service"""
        if not authorization:
            logger.warning(
                "missing_authorization_header",
                service=service_name
            )
            raise AuthenticationException("Authorization header is required")

        if not authorization.startswith("Bearer "):
            logger.warning(
                "invalid_authorization_format",
                service=service_name,
                format=authorization[:20]
            )
            raise AuthenticationException("Invalid authorization format")

        token = authorization[7:]  # Remove "Bearer " prefix

        # Get service-specific token or fall back to global
        expected_token = self.service_tokens.get(service_name) or self.global_token

        if token != expected_token:
            logger.warning(
                "invalid_bearer_token",
                service=service_name,
                token_prefix=token[:10] if token else ""
            )
            raise AuthenticationException("Invalid bearer token")

        logger.debug("authentication_successful", service=service_name)
        return True


# Global auth manager (will be initialized in main.py)
auth_manager: Optional[ServiceAuthManager] = None


def init_auth_manager(global_token: str, service_tokens: Dict[str, Optional[str]]):
    """Initialize global auth manager"""
    global auth_manager
    auth_manager = ServiceAuthManager(global_token, service_tokens)


# Service-specific dependencies
async def verify_translation_auth(authorization: str = Header(None)) -> bool:
    """Dependency for translation service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("translation", authorization)


async def verify_wine_pairing_auth(authorization: str = Header(None)) -> bool:
    """Dependency for wine pairing service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("wine_pairing", authorization)


async def verify_beer_pairing_auth(authorization: str = Header(None)) -> bool:
    """Dependency for beer pairing service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("beer_pairing", authorization)


async def verify_menu_extraction_auth(authorization: str = Header(None)) -> bool:
    """Dependency for menu extraction service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("menu_extraction", authorization)


async def verify_insert_menu_items_auth(authorization: str = Header(None)) -> bool:
    """Dependency for insert menu items service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("insert_menu_items", authorization)


async def verify_create_restaurant_offer_auth(authorization: str = Header(None)) -> bool:
    """Dependency for create restaurant offer service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("create_restaurant_offer", authorization)


async def verify_generate_ai_image_auth(authorization: str = Header(None)) -> bool:
    """Dependency for generate ai image service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("generate_ai_image", authorization)


async def verify_ai_analytics_auth(authorization: str = Header(None)) -> bool:
    """Dependency for ai analytics service authentication"""
    if auth_manager is None:
        raise RuntimeError("Auth manager not initialized")
    return auth_manager.verify_service_token("ai_analytics", authorization)
