# src/utils/greeting_handler.py
import re
import random
from typing import Tuple, Optional


class GreetingHandler:
    """Handler for detecting and responding to greetings"""

    # Singleton instance
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(GreetingHandler, cls).__new__(cls)
            cls._instance._initialize()
        return cls._instance

    def _initialize(self):
        """Initialize patterns and responses"""
        # Common greeting patterns with word boundaries to match whole words
        self.greeting_patterns = [
            # English Greetings
            r'\b(hi|hello|hey|howdy|greetings|good morning|good afternoon|good evening|good day)\b',
            r'\bho+la\b',  # Spanish greeting with possible repeated 'o'
            r'\bhiy+a\b',  # "Hiya" with possible repeated 'y'
            r'\bhel+o+\b',  # "Hello" with possible repeated letters
            r'\bhey+\b',   # "Hey" with possible repeated 'y'
            r'\bhi+\b',    # "Hi" with possible repeated 'i'
            r'\byo+\b',    # "Yo" with possible repeated 'o'
            r'how are you(\s|\?|$)',
            r'what\'?s up',
            r'nice to (meet|see) you',
            r'\bhiya\b',
            r'\bsup\b',
            r'\bwhat up\b',
            r'\bhow\'?s it going\b',
            r'\bhow\'?s everything\b',
            r'\bhow\'?s life\b',
            r'\bhow\'?s your day\b',
            r'\bhow\'?ve you been\b',
            r'\bwhat\'?s new\b',
            r'\bany news\b',
            r'\bhowdy partner\b',
            r'\bheya\b',
            r'\bhallo\b',
            r'\bhey there\b',
            r'\btop of the morning\b',

            # International Greetings
            r'\bbonjour\b',  # French greeting
            r'\bciao\b',  # Italian greeting
            r'\bnamaste\b',  # Hindi greeting
            r'\bsalam\b',  # Arabic greeting
            r'\bassalamu alaikum\b',  # Islamic greeting
            r'\bshalom\b',  # Hebrew greeting

            # Russian Greetings (Transliterated)
            r'\bprivet\b',  # "Privet" - Informal Hello
            r'\bzdravstvuyte\b',  # "Zdravstvuyte" - Formal Hello
            r'\bdobroe utro\b',  # "Dobroe utro" - Good morning
            r'\bdobryy den\b',  # "Dobryy den" - Good afternoon
            r'\bdobryy vecher\b',  # "Dobryy vecher" - Good evening
            r'\bkak dela\b',  # "Kak dela" - How are you?
            r'\bkak pozhivayesh\b',  # "Kak pozhivayesh" - How have you been?

            # Arabic Greetings (Transliterated)
            r'\bmarhaban\b',  # "Marhaban" - Hello
            r'\bahlan\b',  # "Ahlan" - Informal Hello
            r'\bassalamu alaykum\b',  # "As-salamu alaykum" - Peace be upon you
            r'\bsabah al-khair\b',  # "Sabah al-khair" - Good morning
            r'\bmasa al-khair\b',  # "Masa al-khair" - Good evening
            r'\bkayfa halak\b',  # "Kayfa halak" (m) - How are you?
            r'\bkayfa halik\b',  # "Kayfa halik" (f) - How are you?
            r'\bkayfa al-umur\b',  # "Kayfa al-umur" - How’s everything?
            r'\bakhbarak\b',  # "Akhbarak" (m) - Any news?
            r'\bakhbarik\b',  # "Akhbarik" (f) - Any news?
        ]
        self.compiled_patterns = [re.compile(
            pattern, re.IGNORECASE) for pattern in self.greeting_patterns]

        # List of greeting responses to choose from for variety
        self.greeting_responses = [
            "Hello! How can I help you today?",
            "Hi there! What can I assist you with?",
            "Hey! How can I be of service?",
            "Greetings! How may I assist you?",
            "Hello! I'm here to help. What would you like to know?",
            "Hi! I'm your assistant. What can I help you with?",
            "Hello there! I'm ready to assist you. What's on your mind?",
            "Hey! I'm here to provide information. What are you looking for?",
            "Hi! How can I assist you today?"
        ]

        # Special responses for "how are you" type greetings
        self.how_are_you_responses = [
            "I'm doing great, thanks for asking! How can I help you today?",
            "I'm well, thank you! How may I assist you?",
            "I'm fine, thanks! What can I help you with?",
            "Doing well! I'm ready to help with whatever you need."
        ]

    def is_greeting(self, query: str) -> Tuple[bool, Optional[str]]:
        """
        Check if the query is a greeting

        Args:
            query (str): The user query

        Returns:
            Tuple[bool, Optional[str]]: (is_greeting, appropriate_response)
        """
        # Convert to lowercase for case-insensitive matching
        query_lower = query.lower().strip()

        # Skip detection for longer queries (likely not just greetings)
        word_count = len(query_lower.split())
        if word_count > 10:
            return False, None

        # Check if query matches any greeting pattern
        is_how_are_you = False

        for pattern in self.compiled_patterns:
            if re.search(pattern, query_lower):
                # Special case for "how are you" type queries
                if "how are you" in query_lower:
                    is_how_are_you = True
                return True, self._get_response(is_how_are_you)

        return False, None

    def _get_response(self, is_how_are_you: bool = False) -> str:
        """
        Get an appropriate greeting response

        Args:
            is_how_are_you (bool): Whether this is a "how are you" type greeting

        Returns:
            str: A greeting response
        """
        if is_how_are_you:
            return random.choice(self.how_are_you_responses)
        return random.choice(self.greeting_responses)