"""Email parsing utilities."""
import email
from email.header import decode_header
from typing import Dict


def get_email_content(msg) -> Dict:
    """Ekstraktuje treść emaila z obiektu email.message.Message."""
    email_data = {
        'subject': '',
        'from': '',
        'body': '',
        'date': '',
        'message_id': '',
        'in_reply_to': '',
        'references': '',
    }
    
    # Subject
    if msg['Subject']:
        subject, encoding = decode_header(msg['Subject'])[0]
        if isinstance(subject, bytes):
            try:
                email_data['subject'] = subject.decode(encoding or 'utf-8')
            except:
                email_data['subject'] = subject.decode('utf-8', errors='ignore')
        else:
            email_data['subject'] = str(subject)
    
    # From
    email_data['from'] = msg.get('From', '')
    email_data['date'] = msg.get('Date', '')
    email_data['message_id'] = msg.get('Message-ID', '')
    email_data['in_reply_to'] = msg.get('In-Reply-To', '')
    email_data['references'] = msg.get('References', '')
    
    # Body
    if msg.is_multipart():
        for part in msg.walk():
            content_type = part.get_content_type()
            if content_type == 'text/plain':
                try:
                    email_data['body'] = part.get_payload(decode=True).decode('utf-8', errors='ignore')
                    break
                except:
                    pass
    else:
        try:
            email_data['body'] = msg.get_payload(decode=True).decode('utf-8', errors='ignore')
        except:
            email_data['body'] = ''
    
    return email_data


def detect_imap_server(email_address: str) -> str:
    """Automatyczne wykrywanie serwera IMAP na podstawie domeny."""
    domain = email_address.split('@')[1].lower()
    
    imap_servers = {
        'gmail.com': 'imap.gmail.com',
        'outlook.com': 'outlook.office365.com',
        'hotmail.com': 'outlook.office365.com',
        'yahoo.com': 'imap.mail.yahoo.com',
        'wp.pl': 'imap.wp.pl',
        'o2.pl': 'imap.o2.pl',
        'interia.pl': 'imap.poczta.interia.pl',
    }
    
    return imap_servers.get(domain, f'imap.{domain}')
