from analogai.foundation.common.design_patterns.state_machine import State
from analogai.foundation.common.logging.app_logger import app_logger
from analogai.deepthink.application.usecases.learning.make_direct_statement.utils.modifier_util import modifiers_match


class FindStatementState(State):
    def __init__(self, state_machine, statement_service):
        super().__init__(state_machine)
        self._statement_service = statement_service

    def execute(self):
        app_logger.info(f"Finding existing statement: subject={repr(self.context.subject_notion)}, complement={repr(self.context.complement_notion)}, relation={self.context.relation}")
        statement = self._find_statement()
        if statement:
            app_logger.info(f"Found existing statement: {repr(statement)}")
        else:
            app_logger.info("No existing statement found, will create new")
        return self._transition(statement)

    def _find_statement(self):
        relation = self.context.relation
        statement = self._statement_service.find(
            subject_notion=self.context.subject_notion,
            complement_notion=self.context.complement_notion,
            relation=relation,
            modifier=self.context.modifier,
        )
        if statement and not modifiers_match(statement.modifier, self.context.modifier):
            return None
        if statement:
            self.context.statement = statement
        return statement

    def _transition(self, statement):
        if not statement:
            return self._transition_to_create()
        return self._transition_to_check_update_applicable()

    def _transition_to_create(self):
        return self.state_machine.state_to_create_statement()

    def _transition_to_check_update_applicable(self):
        return self.state_machine.state_to_update_statement()
