"""
Shared email utilities for PraisonAI bots.

Contains common email logic used by both EmailBot (IMAP/SMTP) and AgentMailBot (API).
"""

from __future__ import annotations

from typing import Dict, Set

# Headers that indicate auto-generated/auto-reply emails
AUTO_REPLY_HEADERS: Set[str] = {
    "auto-submitted",
    "x-auto-response-suppress",
    "x-autoreply",
    "x-autorespond",
    "x-autogenerated",
    "precedence",  # Often set to "bulk" or "auto_reply"
}

# Sender patterns to never reply to (prevents loops)
BLOCKED_SENDERS: Set[str] = {
    "mailer-daemon",
    "postmaster",
    "noreply",
    "no-reply",
    "donotreply",
    "do-not-reply",
    "bounce",
    "auto",
    "daemon",
}


def is_auto_reply(headers: Dict[str, str]) -> bool:
    """Check if email headers indicate an auto-reply.
    
    Args:
        headers: Dictionary of email headers (case-insensitive keys recommended).
        
    Returns:
        True if the email appears to be an auto-reply.
    """
    headers_lower = {k.lower(): v for k, v in headers.items()}
    
    for header in AUTO_REPLY_HEADERS:
        if header in headers_lower:
            value = headers_lower[header]
            # auto-submitted: auto-replied, auto-generated, auto-notified
            if header == "auto-submitted" and value and value.lower() != "no":
                return True
            # precedence: bulk, junk, list, auto_reply
            if header == "precedence" and value and value.lower() in ("bulk", "junk", "auto_reply"):
                return True
            # Other headers: any non-empty value indicates auto-reply
            if header not in ("auto-submitted", "precedence") and value:
                return True
    
    return False


def is_blocked_sender(sender: str) -> bool:
    """Check if sender should be blocked (system addresses, no-reply, etc.).
    
    Args:
        sender: Email address or display name of sender.
        
    Returns:
        True if the sender should not receive replies.
    """
    if not sender:
        return True
    
    sender_lower = sender.lower()
    return any(blocked in sender_lower for blocked in BLOCKED_SENDERS)


def extract_email_address(full_address: str) -> str:
    """Extract email address from a full address string.
    
    Args:
        full_address: Full address like "John Doe <john@example.com>" or "john@example.com"
        
    Returns:
        Just the email address part.
    """
    if not full_address:
        return ""
    
    # Handle "Name <email>" format
    if "<" in full_address and ">" in full_address:
        start = full_address.index("<") + 1
        end = full_address.index(">")
        return full_address[start:end].strip()
    
    return full_address.strip()


def normalize_subject(subject: str, strip_prefixes: bool = True) -> str:
    """Normalize email subject for comparison/threading.
    
    Args:
        subject: Original subject line.
        strip_prefixes: If True, removes Re:, Fwd:, etc.
        
    Returns:
        Normalized subject string.
    """
    if not subject:
        return ""
    
    result = subject.strip()
    
    if strip_prefixes:
        # Remove common reply/forward prefixes
        prefixes = ("re:", "fwd:", "fw:", "aw:", "sv:", "vs:")
        while True:
            lower = result.lower()
            stripped = False
            for prefix in prefixes:
                if lower.startswith(prefix):
                    result = result[len(prefix):].strip()
                    stripped = True
                    break
            if not stripped:
                break
    
    return result
