from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from recruitment.models import Notification, HiringAgency
import datetime


class Command(BaseCommand):
    help = 'Verify the notification system is working correctly'

    def add_arguments(self, parser):
        parser.add_argument(
            '--detailed',
            action='store_true',
            help='Show detailed breakdown of notifications',
        )

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('🔍 Verifying Notification System'))
        self.stdout.write('=' * 50)

        # Check notification counts
        total_notifications = Notification.objects.count()
        pending_notifications = Notification.objects.filter(status='PENDING').count()
        sent_notifications = Notification.objects.filter(status='SENT').count()
        failed_notifications = Notification.objects.filter(status='FAILED').count()

        self.stdout.write(f'\n📊 Notification Counts:')
        self.stdout.write(f'   Total Notifications: {total_notifications}')
        self.stdout.write(f'   Pending: {pending_notifications}')
        self.stdout.write(f'   Sent: {sent_notifications}')
        self.stdout.write(f'   Failed: {failed_notifications}')

        # Agency messaging system has been removed - replaced by Notification system
        self.stdout.write(f'\n💬 Message System:')
        self.stdout.write(f'   Agency messaging system has been replaced by Notification system')

        # Check admin user notifications
        admin_users = User.objects.filter(is_staff=True)
        self.stdout.write(f'\n👤 Admin Users ({admin_users.count()}):')

        for admin in admin_users:
            admin_notifications = Notification.objects.filter(recipient=admin).count()
            admin_unread = Notification.objects.filter(recipient=admin, status='PENDING').count()
            self.stdout.write(f'   {admin.username}: {admin_notifications} notifications ({admin_unread} unread)')

        # Check agency notifications
        # Note: Current Notification model only supports User recipients, not agencies
        # Agency messaging system has been removed
        agencies = HiringAgency.objects.all()
        self.stdout.write(f'\n🏢 Agencies ({agencies.count()}):')

        for agency in agencies:
            self.stdout.write(f'   {agency.name}: Agency messaging system has been removed')

        # Check notification types
        if options['detailed']:
            self.stdout.write(f'\n📋 Detailed Notification Breakdown:')

            # By type
            for notification_type in ['email', 'in_app']:
                count = Notification.objects.filter(notification_type=notification_type).count()
                if count > 0:
                    self.stdout.write(f'   {notification_type}: {count}')

            # By status
            for status in ['pending', 'sent', 'read', 'failed', 'retrying']:
                count = Notification.objects.filter(status=status).count()
                if count > 0:
                    self.stdout.write(f'   {status}: {count}')

        # System health check
        self.stdout.write(f'\n🏥 System Health Check:')

        issues = []

        # Check for failed notifications
        if failed_notifications > 0:
            issues.append(f'{failed_notifications} failed notifications')

        # Check for admin users without notifications
        admin_with_no_notifications = admin_users.filter(
            notifications__isnull=True
        ).count()
        if admin_with_no_notifications > 0 and total_notifications > 0:
            issues.append(f'{admin_with_no_notifications} admin users with no notifications')

        if issues:
            self.stdout.write(self.style.WARNING('   ⚠️  Issues found:'))
            for issue in issues:
                self.stdout.write(f'      - {issue}')
        else:
            self.stdout.write(self.style.SUCCESS('   ✅ No issues detected'))

        # Recent activity
        recent_notifications = Notification.objects.filter(
            created_at__gte=datetime.datetime.now() - datetime.timedelta(hours=24)
        ).count()

        self.stdout.write(f'\n🕐 Recent Activity (last 24 hours):')
        self.stdout.write(f'   New notifications: {recent_notifications}')

        # Summary
        self.stdout.write(f'\n📋 Summary:')
        if total_notifications > 0 and failed_notifications == 0:
            self.stdout.write(self.style.SUCCESS('   ✅ Notification system is working correctly'))
        elif failed_notifications > 0:
            self.stdout.write(self.style.WARNING('   ⚠️  Notification system has some failures'))
        else:
            self.stdout.write(self.style.WARNING('   ⚠️  No notifications found - system may not be active'))

        self.stdout.write('\n' + '=' * 50)
        self.stdout.write(self.style.SUCCESS('✨ Verification complete!'))
