from typing import cast, TYPE_CHECKING
from analogai.deepthink.presentation.interpreters.interpreter_result import InterpreterResult
from analogai.deepthink.presentation.interpreters.interpreter_registry import InterpreterRegistry
from analogai.deepthink.presentation.interpreters.result_resolver import InterpreterResultResolver

if TYPE_CHECKING:
    from analogai.deepthink.presentation.factories.interpreters_factory import InterpretersFactory


class InterpreterPipeline:
    def __init__(self, interpreters_factory: "InterpretersFactory"):
        self._interpreters_factory = interpreters_factory
        self._interpreters: InterpreterRegistry | None = None
        self._result_resolver = InterpreterResultResolver()

    def _get_interpreters(self) -> InterpreterRegistry:
        if self._interpreters is None:
            try:
                self._interpreters = self._interpreters_factory.create_registry()
            except AttributeError:
                self._interpreters = InterpreterRegistry(self._interpreters_factory.create_all())
        return self._interpreters

    def run(self, parsed_message, user_agent, message_text: str) -> InterpreterResult | None | bool:
        for interpreter in self._get_interpreters().all():
            result = interpreter.interpret(parsed_message, user_agent, message_text)
            resolved = self._result_resolver.resolve(result)
            if self._result_resolver.is_resolved(resolved):
                return cast(InterpreterResult | bool | None, resolved)
        return None

