import time
import logging
from collections import defaultdict

logger = logging.getLogger(__name__)

class EmailMetrics:
    def __init__(self):
        self.domain_metrics = defaultdict(lambda: {
            'emails_sent': 0,
            'emails_throttled': 0,
            'total_delay': 0,
            'errors': 0,
            'last_updated': time.time()
        })

    def record_sent(self, domain):
        """Records an email successfully sent to the given domain."""
        self.domain_metrics[domain]['emails_sent'] += 1
        self.domain_metrics[domain]['last_updated'] = time.time()
        logger.debug(f"Email sent recorded for domain: {domain}")

    def record_throttled(self, domain):
        """Records an email being throttled for the given domain."""
        self.domain_metrics[domain]['emails_throttled'] += 1
        self.domain_metrics[domain]['last_updated'] = time.time()
        logger.debug(f"Email throttled recorded for domain: {domain}")

    def record_delay(self, domain, delay):
        """Records the delay experienced for an email to the given domain."""
        self.domain_metrics[domain]['total_delay'] += delay
        self.domain_metrics[domain]['last_updated'] = time.time()
        logger.debug(f"Delay recorded for domain: {domain}, delay: {delay}")

    def record_error(self, domain):
        """Records an error encountered while sending to the given domain."""
        self.domain_metrics[domain]['errors'] += 1
        self.domain_metrics[domain]['last_updated'] = time.time()
        logger.error(f"Error recorded for domain: {domain}")

    def get_metrics(self, domain=None):
        """Returns the metrics for a specific domain or all domains."""
        if domain:
            return self.domain_metrics.get(domain, {
                'emails_sent': 0,
                'emails_throttled': 0,
                'total_delay': 0,
                'errors': 0,
                'last_updated': time.time()
            })
        else:
            return self.domain_metrics

    def get_average_delay(self, domain):
        """Calculates the average delay for a domain."""
        metrics = self.domain_metrics.get(domain)
        if metrics and metrics['emails_sent'] > 0:
            return metrics['total_delay'] / metrics['emails_sent']
        else:
            return 0

# Example usage (can be removed in production, for demonstration only)
if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    metrics = EmailMetrics()
    metrics.record_sent('gmail.com')
    metrics.record_throttled('gmail.com')
    metrics.record_delay('gmail.com', 0.5)
    metrics.record_error('yahoo.com')

    print(metrics.get_metrics('gmail.com'))
    print(metrics.get_metrics('yahoo.com'))
    print(metrics.get_metrics())
    print(f"Average delay for gmail.com: {metrics.get_average_delay('gmail.com')}")