"""
Email auto-sync — polls all active IMAP accounts every 30 seconds.
Simple and reliable: no IDLE, no reconnection issues.
"""
import time
from django.core.management.base import BaseCommand


def _fetch(acct):
    try:
        from clients.management.commands.fetch_emails import fetch_account
        from clients.models import ClientEmailAccount
        acct = ClientEmailAccount.objects.get(pk=acct.pk)
        result = fetch_account(acct)
        if result['created']:
            ts = time.strftime('%H:%M:%S')
            print(f'[{ts}] [{acct.name}] ✅ {result["created"]} new ticket(s) created')
        if result['errors']:
            print(f'[{time.strftime("%H:%M:%S")}] [{acct.name}] ⚠ {result["errors"]}')
    except Exception as e:
        print(f'[{time.strftime("%H:%M:%S")}] [{acct.name}] Error: {e}')


class Command(BaseCommand):
    help = 'Poll all active IMAP accounts every 30s and create tickets from new emails'

    def add_arguments(self, parser):
        parser.add_argument('--interval', type=int, default=30,
                            help='Seconds between checks (default: 30)')

    def handle(self, *args, **options):
        from clients.models import ClientEmailAccount

        interval = options['interval']
        self.stdout.write(self.style.SUCCESS(
            f'Email sync started — checking every {interval}s '
            '(account list re-read each cycle, so new/removed accounts are picked up live)'
        ))

        # Re-query the active accounts every cycle so ALL clients' mailboxes are
        # polled — newly-added accounts are picked up without restarting, and
        # deleted/deactivated ones simply drop off.
        prev = set()
        try:
            while True:
                accounts = list(ClientEmailAccount.objects.filter(is_active=True))
                current = {a.pk for a in accounts}
                if current != prev:
                    ts = time.strftime('%H:%M:%S')
                    self.stdout.write(f'[{ts}] Watching {len(accounts)} active mailbox(es) across all clients:')
                    for a in accounts:
                        self.stdout.write(f'    • {a.email}  (client: {a.client.name if a.client else "—"})')
                    if not accounts:
                        self.stdout.write('    (none active — waiting for an email account to be added)')
                    prev = current
                for acct in accounts:
                    _fetch(acct)
                # Send any AI auto-replies whose human-like delay has elapsed.
                try:
                    from ai_services.auto_reply import send_due_replies
                    n = send_due_replies()
                    if n:
                        self.stdout.write(f'[{time.strftime("%H:%M:%S")}] ✉ sent {n} scheduled auto-repl{"y" if n==1 else "ies"}')
                except Exception as e:
                    self.stdout.write(f'[{time.strftime("%H:%M:%S")}] auto-reply sweep error: {e}')
                time.sleep(interval)
        except KeyboardInterrupt:
            self.stdout.write('\nStopping email sync...')
