import threading

from analogai.foundation.common.logging.app_logger import app_logger
from analogai.deepthink.features.notion_enrichment.enricher_service import NotionEnricherService
from analogai.deepthink.features.notion_enrichment.ports import NotionCreatedObserverPort


class NotionEnrichmentObserver(NotionCreatedObserverPort):
    def __init__(self, enricher_service: NotionEnricherService):
        self._enricher_service = enricher_service

    def on_notion_created(self, notion: object) -> None:
        if not notion:
            return
        thread = threading.Thread(
            target=self._run_enrichment_safe,
            args=(notion,),
            daemon=True,
            name="NotionEnrichmentWorker",
        )
        thread.start()

    def _run_enrichment_safe(self, notion: object) -> None:
        try:
            self._enricher_service.handle_notion_created(notion)
        except Exception as exc:
            app_logger.error(f"Notion enrichment failed: {exc}", exc_info=True)
