"""Conversation history utilities for Email Responder."""
import email
import re
from typing import Dict, List, Tuple
from llmass.organizer.parser import get_email_content


def get_greeting(lang: str) -> str:
    """
    Zwraca pozdrowienie w danym języku.
    
    Args:
        lang: Kod języka ('pl', 'en', 'de', 'fr', etc.)
    
    Returns:
        Pozdrowienie w odpowiednim języku
    """
    greetings = {
        'pl': 'Z poważaniem,',
        'en': 'Best regards,',
        'de': 'Mit freundlichen Grüßen,',
        'fr': 'Cordialement,',
        'es': 'Atentamente,',
        'it': 'Cordiali saluti,',
    }
    
    return greetings.get(lang, greetings['en'])


def detect_language(text: str) -> str:
    """
    Wykrywa język emaila na podstawie charakterystycznych słów.
    
    Args:
        text: Tekst do analizy (body + subject)
    
    Returns:
        Kod języka: 'pl', 'en', 'de', 'fr', etc.
    """
    if not text:
        return 'en'
    
    text_lower = text.lower()
    
    # Characteristic words for each language
    lang_patterns = {
        'pl': ['dziękuję', 'dziekuje', 'proszę', 'prosze', 'wiadomość', 'wiadomosc', 
               'pozdrawiam', 'witam', 'szanowny', 'pani', 'pana', 'będę', 'bede'],
        'de': ['danke', 'bitte', 'sehr', 'guten', 'herzlich', 'freundlich', 
               'herr', 'frau', 'beste', 'grüße', 'grusse', 'ihrer', 'vielen'],
        'fr': ['merci', 'bonjour', 'vous', 'votre', 'cordialement', 'salut',
               'merci beaucoup', 'madame', 'monsieur'],
        'es': ['gracias', 'hola', 'buenos', 'días', 'saludos', 'usted',
               'señor', 'señora'],
        'it': ['grazie', 'ciao', 'buongiorno', 'cordiali', 'saluti',
               'signore', 'signora'],
        'en': ['thank', 'thanks', 'please', 'regards', 'sincerely', 'hello',
               'dear', 'best', 'kind', 'appreciate', 'help', 'information',
               'update', 'available', 'message', 'email'],
    }
    
    # Count matches for each language
    scores = {}
    for lang, patterns in lang_patterns.items():
        score = sum(1 for pattern in patterns if pattern in text_lower)
        if score > 0:
            scores[lang] = score
    
    # Return language with highest score
    if scores:
        return max(scores, key=scores.get)
    
    # Default to English
    return 'en'


def fetch_conversation_history(ctx, sender_email: str, limit: int = 3) -> Tuple[List[Dict], List[Dict]]:
    """
    Pobiera pełną historię konwersacji z nadawcą (wysłane i otrzymane emaile).
    
    Args:
        ctx: Context object with imap/client
        sender_email: Email nadawcy
        limit: Maksymalna liczba wiadomości do pobrania (dla każdego typu)
    
    Returns:
        Tuple (sent_emails, received_emails) - każda lista sorted newest first
    """
    sent_history = []
    received_history = []
    
    try:
        client = getattr(ctx, 'client', None)
        
        # Znajdź foldery
        result, data = client.safe_list() if client else ctx.imap.list()
        if result != 'OK' or not data:
            return sent_history, received_history
        
        sent_folder = None
        inbox_folder = 'INBOX'
        
        for raw in data:
            if not raw:
                continue
            line = raw.decode(errors='ignore')
            parts = line.split('"')
            if len(parts) >= 5:
                name = parts[3].strip()
                name_lower = name.lower()
                if 'sent' in name_lower or 'gesendet' in name_lower or 'wyslane' in name_lower:
                    sent_folder = name
        
        # 1. Pobierz wysłane emaile (TO sender)
        if sent_folder:
            try:
                result, data = client.safe_select(sent_folder, readonly=True) if client else ctx.imap.select(sent_folder, readonly=True)
                if result == 'OK':
                    search_criteria = f'TO "{sender_email}"'
                    result, data = client.safe_uid('SEARCH', None, search_criteria) if client else ctx.imap.uid('SEARCH', None, search_criteria)
                    
                    if result == 'OK' and data and data[0]:
                        email_ids = data[0].split()
                        if email_ids:
                            email_ids = email_ids[-limit:] if len(email_ids) > limit else email_ids
                            email_ids.reverse()
                            
                            for email_id in email_ids:
                                try:
                                    result, data = client.safe_uid('FETCH', email_id, '(RFC822)') if client else ctx.imap.uid('FETCH', email_id, '(RFC822)')
                                    if result == 'OK' and data and data[0]:
                                        raw_email = data[0][1]
                                        if raw_email:
                                            msg = email.message_from_bytes(raw_email)
                                            email_data = get_email_content(msg)
                                            if email_data:
                                                sent_history.append(email_data)
                                except Exception:
                                    continue
            except Exception:
                pass
        
        # 2. Pobierz otrzymane emaile (FROM sender)
        try:
            result, data = client.safe_select(inbox_folder, readonly=True) if client else ctx.imap.select(inbox_folder, readonly=True)
            if result == 'OK':
                search_criteria = f'FROM "{sender_email}"'
                result, data = client.safe_uid('SEARCH', None, search_criteria) if client else ctx.imap.uid('SEARCH', None, search_criteria)
                
                if result == 'OK' and data and data[0]:
                    email_ids = data[0].split()
                    if email_ids:
                        email_ids = email_ids[-limit:] if len(email_ids) > limit else email_ids
                        email_ids.reverse()
                        
                        for email_id in email_ids:
                            try:
                                result, data = client.safe_uid('FETCH', email_id, '(RFC822)') if client else ctx.imap.uid('FETCH', email_id, '(RFC822)')
                                if result == 'OK' and data and data[0]:
                                    raw_email = data[0][1]
                                    if raw_email:
                                        msg = email.message_from_bytes(raw_email)
                                        email_data = get_email_content(msg)
                                        if email_data:
                                            received_history.append(email_data)
                            except Exception:
                                continue
        except Exception:
            pass
        
        return sent_history, received_history
        
    except Exception:
        return sent_history, received_history
