from analogai.foundation.common.logging.app_logger import app_logger
from analogai.foundation.common.utils.statement_serializers.notion_serializer import (
    serialize_notion_expression,
)

from analogai.deepthink.application.usecases.learning.make_notion_statement.models import (
    MakeNotionStatementResponse,
)
from analogai.deepthink.application.usecases.learning.make_notion_statement.ports import (
    MakeNotionStatementOutputPort,
)
from analogai.deepthink.presentation.presenters.presenter_response import PresenterResponse
from analogai.foundation.modules.fact.services.fact_service import FactServicePort
from analogai.foundation.modules.fact.utils.fact_context import get_current_turn_id


class MakeNotionStatementPresenter(MakeNotionStatementOutputPort):
    def __init__(self, fact_service: FactServicePort | None = None):
        self._fact_service = fact_service

    def output_notion_statement_saved(
        self,
        response: MakeNotionStatementResponse,
    ) -> PresenterResponse:
        app_logger.info("Outputting notion statement saved")
        notion_id = response.notion_id
        turn_id = get_current_turn_id()
        if self._fact_service is not None and notion_id and turn_id:
            try:
                self._fact_service.link_notion(notion_id, turn_id)
            except Exception:
                try:
                    app_logger.debug("Failed to link notion %s to turn %s", notion_id, turn_id)
                except Exception:
                    pass
        message = serialize_notion_expression(response.notion_expression)
        return PresenterResponse(message=message)
