"""
Celery tasks for ticket email processing.
"""

import logging
from celery import shared_task

logger = logging.getLogger(__name__)


@shared_task(
    name='tickets.fetch_incoming_emails',
    bind=True,
    max_retries=3,
    default_retry_delay=60,
    autoretry_for=(Exception,),
)
def fetch_incoming_emails(self):
    """
    Celery task to fetch and process incoming ticket emails.
    Processes emails for all active email addresses (platform and business).

    This task should be scheduled to run periodically (e.g., every minute)
    via Celery Beat.

    Example Celery Beat configuration:
        CELERY_BEAT_SCHEDULE = {
            'fetch-ticket-emails': {
                'task': 'tickets.fetch_incoming_emails',
                'schedule': 60.0,  # Every 60 seconds
            },
        }
    """
    from .email_receiver import TicketEmailReceiver, PlatformEmailReceiver
    from .models import TicketEmailAddress
    from smoothschedule.platform.admin.models import PlatformEmailAddress

    total_processed = 0
    results = []

    # Process platform email addresses (default one for tickets)
    try:
        default_platform_email = PlatformEmailAddress.objects.filter(
            is_active=True,
            is_default=True
        ).first()

        if default_platform_email:
            try:
                receiver = PlatformEmailReceiver(default_platform_email)
                processed = receiver.fetch_and_process_emails()
                total_processed += processed
                results.append({
                    'address': default_platform_email.display_name,
                    'type': 'platform',
                    'processed': processed,
                    'status': 'success'
                })
                logger.info(f"[Platform: {default_platform_email.display_name}] Processed {processed} emails")
            except Exception as e:
                logger.error(f"[Platform: {default_platform_email.display_name}] Error processing emails: {e}")
                results.append({
                    'address': default_platform_email.display_name,
                    'type': 'platform',
                    'processed': 0,
                    'status': 'error',
                    'error': str(e)
                })
    except Exception as e:
        logger.error(f"Error fetching platform email addresses: {e}")

    # Process tenant/business email addresses
    email_addresses = TicketEmailAddress.objects.filter(is_active=True)

    for email_address in email_addresses:
        try:
            receiver = TicketEmailReceiver(email_address)
            processed = receiver.fetch_and_process_emails()
            total_processed += processed
            results.append({
                'address': email_address.display_name,
                'type': 'tenant',
                'processed': processed,
                'status': 'success'
            })
            logger.info(f"[Tenant: {email_address.display_name}] Processed {processed} emails")
        except Exception as e:
            logger.error(f"[Tenant: {email_address.display_name}] Error processing emails: {e}")
            results.append({
                'address': email_address.display_name,
                'type': 'tenant',
                'processed': 0,
                'status': 'error',
                'error': str(e)
            })

    logger.info(f"Processed {total_processed} total incoming ticket emails from {len(results)} addresses")

    return {
        'status': 'success',
        'processed': total_processed,
        'results': results,
    }


@shared_task(name='tickets.test_email_connection')
def test_email_connection():
    """
    Task to test IMAP connection.

    Returns:
        Dict with success status and message
    """
    from .email_receiver import test_imap_connection

    success, message = test_imap_connection()

    return {
        'success': success,
        'message': message,
    }
