from typing import List, Optional
from analogai.foundation.extensions.fallback.repositories.fallback_repository import FallbackRepository
from analogai.foundation.extensions.fallback.fallback import Fallback
from analogai.foundation.common.logging.app_logger import app_logger
from typeguard import typechecked


class FallbackService:
    def __init__(self, fallback_repository: FallbackRepository):
        self.fallback_repository = fallback_repository

    @typechecked
    def create(self, user_id: str, agent_id: str, user_question: str) -> Fallback:
        app_logger.debug(f"Creating fallback with user_id={user_id}, agent_id={agent_id}, user_question='{user_question[:50]}...'")
        fallback = Fallback(
            user_id=user_id,
            agent_id=agent_id,
            user_question=user_question
        )
        created_fallback = self.fallback_repository.create(fallback)
        app_logger.debug(f"Created Fallback, user_question='{user_question[:50]}...' (fallback_id: {created_fallback.id})")
        return created_fallback

    @typechecked
    def find_by_id(self, fallback_id: str) -> Optional[Fallback]:
        result = self.fallback_repository.find_by_id(fallback_id)
        if result:
            app_logger.debug(f"Found Fallback, user_question='{result.user_question[:50]}...' (fallback_id: {result.id})")
        else:
            app_logger.warning(f"Fallback not found: id={fallback_id}")
        return result

    @typechecked
    def find_by_agent_id(self, agent_id: str) -> List[Fallback]:
        return self.fallback_repository.find_by_agent_id(agent_id)
