from __future__ import annotations

from typing import Optional

from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.application.value_objects.search_result import SearchResult
from analogai.deepthink.messaging.commands import RememberCommand, SearchCommand
from analogai.deepthink.messaging.question_answering.question_routing_service import (
    QuestionRoutingService,
)
from analogai.deepthink.presentation.preprocessing.previous_messages_stack import PreviousMessagesStack


class ChatFlow:
    def __init__(
        self,
        remember_command: RememberCommand,
        search_command: SearchCommand,
        *,
        input_router: QuestionRoutingService | None = None,
    ):
        if input_router is None:
            raise ValueError("input_router is required")
        self._question_router = input_router
        self._remember_command = remember_command
        self._search_command = search_command

    def detect_question(self, text: str) -> bool:
        return self._question_router.is_question_message(text)

    def handle_question(
        self,
        text: str,
        user_agent: UserAgent,
        stack: PreviousMessagesStack,
    ) -> Optional[SearchResult]:
        answer = self._search_command.execute(text, user_agent, stack)
        if answer is None:
            return SearchResult.from_sources("I don't know")
        return answer

    def handle_statement(
        self,
        text: str,
        user_agent: UserAgent,
        stack: PreviousMessagesStack,
    ) -> Optional[str]:
        return self._remember_command.execute(text, user_agent, stack)

    def process_message(
        self,
        text: str,
        user_agent: UserAgent,
        stack: PreviousMessagesStack,
    ) -> Optional[str]:
        if self.detect_question(text):
            result = self.handle_question(text, user_agent, stack)
            return result.text if result else None
        return self.handle_statement(text, user_agent, stack)
