"""Draft saving utilities for Email Responder."""
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
from typing import Dict


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


def resolve_drafts_folder_name(ctx) -> str:
    """
    Znajduje istniejący folder Drafts (wersje robocze) lub zwraca fallback.
    Preferuje INBOX<delim>Drafts, w innym wypadku pierwszy folder zawierający 'draft'.
    """
    try:
        client = getattr(ctx, 'client', None)
        result, data = client.safe_list() if client else ctx.imap.list()
        if result != 'OK' or not data:
            return 'INBOX.Drafts'
        
        folders = []
        for raw in data:
            if not raw:
                continue
            line = raw.decode(errors='ignore')
            parts = line.split('"')
            if len(parts) >= 5:
                name = parts[3]
                folders.append(name.strip())
        
        # Preferuj INBOX<delim>Drafts
        for f in folders:
            if f.lower() in ['inbox.drafts', 'inbox/drafts', 'drafts']:
                return f
        
        # Fallback: pierwszy zawierający 'draft'
        for f in folders:
            if 'draft' in f.lower():
                return f
    except Exception:
        pass
    
    return 'INBOX.Drafts'


def save_draft(ctx, original_email: Dict, response: str) -> bool:
    """Zapisuje odpowiedź jako draft w folderze Drafts."""
    try:
        msg = MIMEMultipart()
        msg['From'] = ctx.email_address
        msg['To'] = original_email.get('from', '')
        msg['Subject'] = f"Re: {original_email.get('subject', '')}"
        msg['In-Reply-To'] = original_email.get('message_id', '')
        msg['References'] = original_email.get('message_id', '')
        msg['Date'] = datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
        msg.attach(MIMEText(response, 'plain', 'utf-8'))
        
        drafts_folder = resolve_drafts_folder_name(ctx)
        client = getattr(ctx, 'client', None)
        
        if client:
            result, data = client.safe_append(drafts_folder, '', None, msg.as_bytes())
        else:
            result, data = ctx.imap.append(drafts_folder, '', None, msg.as_bytes())
        
        if result == 'OK':
            print(f"✅ Zapisano jako draft")
            return True
        else:
            print(f"❌ Błąd zapisywania draftu: {result} {data}")
            return False
    except Exception as e:
        print(f"❌ Błąd podczas zapisywania draftu: {e}")
        return False


def is_auto_reply(email_content: Dict) -> bool:
    """Sprawdza czy email jest automatyczną odpowiedzią."""
    auto_reply_indicators = [
        'noreply', 'no-reply', 'donotreply', 
        'mailer-daemon', 'postmaster', 'auto-reply',
        'automated', 'notification'
    ]
    
    sender = email_content.get('from', '').lower()
    subject = email_content.get('subject', '').lower()
    
    for indicator in auto_reply_indicators:
        if indicator in sender or indicator in subject:
            return True
    
    return False
