import re
from typing import Any, Dict, Optional

from filum_utils.clients.filum import FilumClient
from filum_utils.utils.automated_action.enums import (
    TRANSLATION_FORMAT_REGEX,
    ConversationProperty,
    FilumEventName,
    FilumTrackEventProperty,
    SurveyResponseProperty,
)


def generate_dict(
    source: Dict[str, Any],
    property_mappings: Dict[str, str],
) -> Dict[str, Any]:
    result = {}
    for source_key, target_key in property_mappings.items():
        result[target_key] = source.get(source_key)
    return result


def get_survey_response(event_data: Dict[str, Any]) -> Dict[str, Any]:
    if (
        event_data.get(FilumTrackEventProperty.EVENT_NAME)
        != FilumEventName.SURVEY_ANSWERED
    ):
        return {}
    return {
        SurveyResponseProperty.ID: event_data.get(
            FilumTrackEventProperty.SURVEY_RESPONSE_ID
        )
    }


def get_conversation(event_data: Dict[str, Any]) -> Dict[str, Any]:
    if (
        event_data.get(FilumTrackEventProperty.EVENT_NAME)
        not in FilumEventName.get_conversation_event_names()
    ):
        return {}
    return {
        ConversationProperty.ID: event_data.get(FilumTrackEventProperty.CONVERSATION_ID)
    }


def get_follow_up_text_translation(
    event_data: Dict[str, Any],
    filum_client: FilumClient,
) -> Optional[Dict[str, Any]]:
    if (
        event_data.get(FilumTrackEventProperty.EVENT_NAME)
        != FilumEventName.SURVEY_ANSWERED
    ):
        return None

    follow_up_text = event_data.get(FilumTrackEventProperty.FOLLOW_UP_TEXT)
    if not follow_up_text or not re.search(TRANSLATION_FORMAT_REGEX, follow_up_text):
        return None

    survey_id = event_data.get(FilumTrackEventProperty.SURVEY_ID)
    return filum_client.get_survey_default_translations(survey_id)
