"""
API dependency injection.

This module provides dependency injection functions for FastAPI endpoints,
including service instance management and request validation.
"""

import logging
from typing import Annotated

from fastapi import Depends, HTTPException, status

from ..service import EvaluationService

logger = logging.getLogger(__name__)

# Global service instance (initialized once, reused across requests)
_service_instance: EvaluationService | None = None


def get_evaluation_service() -> EvaluationService:
    """
    Get or create the evaluation service instance.
    
    This dependency provides a singleton service instance that's reused
    across all requests, avoiding the overhead of recreating clients.
    
    Returns:
        EvaluationService instance
        
    Raises:
        HTTPException: If service initialization fails
    """
    global _service_instance
    
    if _service_instance is None:
        try:
            logger.info("Initializing EvaluationService...")
            _service_instance = EvaluationService()
            logger.info("EvaluationService initialized successfully")
        except Exception as e:
            logger.error(f"Failed to initialize EvaluationService: {e}")
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail=f"Service initialization failed: {str(e)}"
            )
    
    return _service_instance




# Type aliases for dependency injection
EvaluationServiceDep = Annotated[EvaluationService, Depends(get_evaluation_service)]

