"""
Management command to fetch incoming ticket emails.

Usage:
    # Single fetch
    python manage.py fetch_ticket_emails

    # Run as daemon (continuous polling)
    python manage.py fetch_ticket_emails --daemon

    # Run as daemon with custom interval
    python manage.py fetch_ticket_emails --daemon --interval 30
"""

import time
import logging
from django.core.management.base import BaseCommand

logger = logging.getLogger(__name__)


class Command(BaseCommand):
    help = 'Fetch and process incoming ticket emails from IMAP server'

    def add_arguments(self, parser):
        parser.add_argument(
            '--daemon',
            action='store_true',
            help='Run continuously, polling for new emails'
        )
        parser.add_argument(
            '--interval',
            type=int,
            default=None,
            help='Polling interval in seconds (default: from settings)'
        )

    def handle(self, *args, **options):
        from tickets.email_receiver import TicketEmailReceiver
        from tickets.models import TicketEmailAddress

        # Get all active email addresses (platform-wide and business-specific)
        email_addresses = TicketEmailAddress.objects.filter(is_active=True)

        if not email_addresses.exists():
            self.stderr.write(self.style.ERROR(
                'No active email addresses configured. Please configure email addresses first.'
            ))
            return

        if options['daemon']:
            # Daemon mode - continuous polling
            interval = options['interval'] or 60  # Default to 60 seconds
            self.stdout.write(self.style.SUCCESS(
                f'Starting email fetch daemon (polling every {interval}s for {email_addresses.count()} addresses)...'
            ))

            while True:
                try:
                    # Refresh email addresses in case they changed
                    email_addresses = TicketEmailAddress.objects.filter(is_active=True)

                    total_processed = 0
                    for email_address in email_addresses:
                        receiver = TicketEmailReceiver(email_address)
                        try:
                            processed = receiver.fetch_and_process_emails()
                            total_processed += processed
                            if processed > 0:
                                self.stdout.write(
                                    f'[{email_address.display_name}] Processed {processed} emails'
                                )
                        except Exception as e:
                            self.stderr.write(self.style.ERROR(
                                f'[{email_address.display_name}] Error: {e}'
                            ))
                            logger.exception(f'Error fetching emails for {email_address.display_name}')

                    time.sleep(interval)

                except KeyboardInterrupt:
                    self.stdout.write(self.style.WARNING('\nShutting down...'))
                    break
                except Exception as e:
                    self.stderr.write(self.style.ERROR(f'Error: {e}'))
                    logger.exception('Error in email fetch daemon')
                    time.sleep(interval)

        else:
            # Single fetch
            self.stdout.write(f'Fetching emails from {email_addresses.count()} addresses...')
            total_processed = 0

            for email_address in email_addresses:
                receiver = TicketEmailReceiver(email_address)
                try:
                    processed = receiver.fetch_and_process_emails()
                    total_processed += processed
                    self.stdout.write(
                        f'[{email_address.display_name}] Processed {processed} emails'
                    )
                except Exception as e:
                    self.stderr.write(self.style.ERROR(
                        f'[{email_address.display_name}] Error: {e}'
                    ))
                    logger.exception(f'Error fetching emails for {email_address.display_name}')

            self.stdout.write(self.style.SUCCESS(
                f'Done. Processed {total_processed} total emails.'
            ))
