from analogai.deepthink.application.value_objects.user_agent import UserAgent
from analogai.deepthink.features.notion_enrichment.models import EnrichmentResult, EnrichmentSuggestion
from analogai.deepthink.features.notion_enrichment.ports import NotionEnrichmentGatewayPort
from analogai.deepthink.presentation.parsers.json_sentence_parser import parse_json
from analogai.deepthink.presentation.parsers.utils.relationship_type_normalizer import tag_key_to_relationship_type
from analogai.deepthink.presentation.intent_type import IntentType
from analogai.foundation.common.logging.app_logger import app_logger

USER_MESSAGE_TEMPLATE = "Notion: {}"


class LlmEnrichmentGatewayAdapter(NotionEnrichmentGatewayPort):
    def __init__(self, completion_provider):
        self._completion_provider = completion_provider

    def enrich(self, notion_caption: str, user_agent: UserAgent) -> EnrichmentResult:
        user_message = USER_MESSAGE_TEMPLATE.format(notion_caption)
        app_logger.info("Notion enrichment request: caption='%s'", notion_caption)
        response = self._completion_provider.generate_completion(user_message)
        parsed_list = parse_json(response or "{}")
        app_logger.info(
            "Notion enrichment response: caption='%s', parsed_items=%d",
            notion_caption,
            len(parsed_list),
        )
        suggestions = []
        skipped_intent = 0
        skipped_missing_fields = 0
        skipped_unrecognized_relation = 0
        skipped_empty_subject_object = 0
        for parsed in parsed_list:
            intent_value = parsed.intent_type
            if isinstance(intent_value, IntentType):
                intent_value = intent_value.value
            if (intent_value or "").strip().lower() != IntentType.MAKING_STATEMENT.value:
                skipped_intent += 1
                continue
            if not parsed.data or not parsed.data.subject or not parsed.data.complement or not parsed.data.relationship_phrase:
                skipped_missing_fields += 1
                continue
            rel_type = tag_key_to_relationship_type(parsed.data.relationship_phrase)
            if rel_type is None:
                skipped_unrecognized_relation += 1
                continue
            subj = (parsed.data.subject or "").strip().lower()
            comp = (parsed.data.complement or "").strip().lower()
            if not subj or not comp:
                skipped_empty_subject_object += 1
                continue
            suggestions.append(
                EnrichmentSuggestion(
                    subject_caption=subj,
                    relationship_type=rel_type,
                    complement_caption=comp,
                )
            )
        app_logger.info(
            "Notion enrichment parsed summary: caption='%s', suggestions=%d, skipped_intent=%d, skipped_missing_fields=%d, skipped_unrecognized_relation=%d, skipped_empty_subject_object=%d",
            notion_caption,
            len(suggestions),
            skipped_intent,
            skipped_missing_fields,
            skipped_unrecognized_relation,
            skipped_empty_subject_object,
        )
        return EnrichmentResult(notion_caption=notion_caption, suggestions=suggestions)
