from analogai.foundation.modules.notion.notion_service import NotionService
from analogai.foundation.common.logging.app_logger import app_logger
from analogai.foundation.common.dtos.notion_expression import NotionExpression

from analogai.deepthink.application.usecases.learning.make_notion_statement.models import (
    MakeNotionStatementRequest,
    MakeNotionStatementResponse,
)
from analogai.deepthink.application.usecases.learning.make_notion_statement.ports import (
    MakeNotionStatementOutputPort,
)


class MakeNotionStatementUseCase:
    def __init__(self, notion_service: NotionService, output_port: MakeNotionStatementOutputPort):
        self._notion_service = notion_service
        self._output_port = output_port

    def execute(self, request: MakeNotionStatementRequest):
        if request is None or request.notion_expression is None:
            return None

        notion_expression = request.notion_expression
        if not isinstance(notion_expression, NotionExpression):
            return None

        app_logger.info(
            "Saving notion statement: caption='%s' attributes=%s",
            notion_expression.caption,
            notion_expression.attributes,
        )

        self._notion_service.upsert_from_expression(
            request.user_agent.user_id,
            request.user_agent.agent_id,
            notion_expression,
        )

        response = MakeNotionStatementResponse(
            user_agent=request.user_agent,
            notion_expression=notion_expression,
            saved=True,
        )
        return self._output_port.output_notion_statement_saved(response)
