"""Meeting request detection from email content."""
import re
from typing import Dict, Optional


def detect_meeting_request(email_content: Dict, lang: str = 'en') -> bool:
    """
    Wykrywa czy email zawiera prośbę o spotkanie/termin.
    
    Args:
        email_content: Słownik z danymi emaila (subject, body)
        lang: Wykryty język emaila
    
    Returns:
        True jeśli email zawiera prośbę o spotkanie
    """
    subject = email_content.get('subject', '').lower()
    body = email_content.get('body', '').lower()
    text = f"{subject} {body}"
    
    # Wzorce dla różnych języków
    meeting_patterns = {
        'pl': [
            'spotkanie', 'spotkać', 'spotkajmy', 'umówmy',
            'termin', 'terminarz', 'kalendarz',
            'kiedy możemy', 'kiedy masz czas', 'wolny termin',
            'ustalmy termin', 'umów', 'rezerwacja',
            'konsultacja', 'rozmowa', 'call', 'telefon',
        ],
        'en': [
            'meeting', 'meet', 'schedule', 'appointment',
            'book', 'booking', 'reservation', 'calendar',
            'when can we', 'when are you available', 'free time',
            'set up a meeting', 'arrange', 'call', 'consultation',
            'available time', 'time slot', 'discuss',
        ],
        'de': [
            'termin', 'treffen', 'besprechung', 'gespräch',
            'vereinbaren', 'terminvereinbarung', 'kalender',
            'wann können wir', 'verfügbar', 'freie zeit',
            'beratung', 'anruf', 'telefonat',
        ],
        'fr': [
            'réunion', 'rendez-vous', 'rencontre', 'entrevue',
            'réserver', 'calendrier', 'disponibilité',
            'quand pouvons-nous', 'temps libre', 'consultation',
        ],
        'es': [
            'reunión', 'cita', 'encuentro', 'reserva',
            'calendario', 'disponibilidad', 'consulta',
            'cuándo podemos', 'tiempo libre',
        ],
    }
    
    # Check patterns for detected language
    patterns = meeting_patterns.get(lang, meeting_patterns['en'])
    
    for pattern in patterns:
        if pattern in text:
            return True
    
    # Universal patterns (phone numbers, email signatures with "let's schedule")
    universal_patterns = [
        r'let[\'s\s]+schedule',
        r'set\s+up\s+a\s+(meeting|call)',
        r'book\s+a\s+(meeting|call)',
    ]
    
    for pattern in universal_patterns:
        if re.search(pattern, text, re.IGNORECASE):
            return True
    
    return False


def extract_meeting_preferences(email_content: Dict, lang: str = 'en') -> Dict:
    """
    Ekstraktuje preferencje dotyczące spotkania z emaila.
    
    Args:
        email_content: Słownik z danymi emaila
        lang: Wykryty język emaila
    
    Returns:
        Słownik z preferencjami: duration, preferred_days, preferred_times, etc.
    """
    body = email_content.get('body', '').lower()
    subject = email_content.get('subject', '').lower()
    text = f"{subject} {body}"
    
    preferences = {
        'duration': None,  # minutes
        'preferred_days': [],
        'preferred_time': None,
        'urgent': False,
    }
    
    # Extract duration
    duration_patterns = [
        (r'(\d+)\s*(?:minute|min|minut)', 1),
        (r'(\d+)\s*(?:hour|hr|godzin|stund)', 60),
        (r'half\s*hour|pół\s*godziny', 30),
        (r'quarter\s*hour|kwadrans', 15),
    ]
    
    for pattern, multiplier in duration_patterns:
        match = re.search(pattern, text, re.IGNORECASE)
        if match:
            if isinstance(multiplier, int):
                if multiplier == 30 or multiplier == 15:
                    preferences['duration'] = multiplier
                else:
                    try:
                        preferences['duration'] = int(match.group(1)) * multiplier
                    except (ValueError, IndexError):
                        pass
            break
    
    # Detect urgency
    urgent_patterns = [
        'urgent', 'pilne', 'asap', 'jak najszybciej',
        'dringend', 'schnell', 'urgent', 'vite',
    ]
    
    for pattern in urgent_patterns:
        if pattern in text:
            preferences['urgent'] = True
            break
    
    # Detect day preferences
    day_patterns = {
        'monday': ['monday', 'poniedziałek', 'montag', 'lundi'],
        'tuesday': ['tuesday', 'wtorek', 'dienstag', 'mardi'],
        'wednesday': ['wednesday', 'środa', 'sroda', 'mittwoch', 'mercredi'],
        'thursday': ['thursday', 'czwartek', 'donnerstag', 'jeudi'],
        'friday': ['friday', 'piątek', 'piatek', 'freitag', 'vendredi'],
    }
    
    for day, patterns in day_patterns.items():
        for pattern in patterns:
            if pattern in text:
                preferences['preferred_days'].append(day)
                break
    
    # Detect time preferences
    time_patterns = [
        (r'morning|rano|vormittag|matin', 'morning'),
        (r'afternoon|popołudnie|popoludnie|nachmittag|après-midi', 'afternoon'),
        (r'evening|wieczór|wieczor|abend|soir', 'evening'),
    ]
    
    for pattern, time_label in time_patterns:
        if re.search(pattern, text, re.IGNORECASE):
            preferences['preferred_time'] = time_label
            break
    
    return preferences
