from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from allauth.socialaccount.models import SocialApp
from django.db.models import Count


class Command(BaseCommand):
    help = 'Debug Google OAuth configuration in detail'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=== Detailed Google OAuth Debug ===\n'))
        
        # Check Sites
        self.stdout.write('Sites:')
        sites = Site.objects.all()
        for site in sites:
            self.stdout.write(f'  ID {site.id}: {site.domain} - {site.name}')
        
        # Check SocialApp
        self.stdout.write('\nSocialApps:')
        apps = SocialApp.objects.all()
        for app in apps:
            self.stdout.write(f'  ID {app.id}: {app.provider} - {app.name}')
            self.stdout.write(f'    Client ID: {app.client_id}')
            self.stdout.write(f'    Sites: {list(app.sites.values_list("domain", flat=True))}')
        
        # Check for duplicates
        self.stdout.write('\nDuplicate Check:')
        provider_counts = SocialApp.objects.values('provider').annotate(count=Count('id'))
        for item in provider_counts:
            if item['count'] > 1:
                self.stdout.write(self.style.ERROR(f'  ✗ Provider "{item["provider"]}" has {item["count"]} entries!'))
            else:
                self.stdout.write(self.style.SUCCESS(f'  ✓ Provider "{item["provider"]}" has {item["count"]} entry'))
        
        # Check SocialApp-Site relationships
        self.stdout.write('\nSocialApp-Site Relationships:')
        for app in SocialApp.objects.all():
            site_count = app.sites.count()
            self.stdout.write(f'  App "{app.name}" is linked to {site_count} site(s)')
            if site_count == 0:
                self.stdout.write(self.style.ERROR('    ✗ No sites linked!'))
            elif site_count > 1:
                self.stdout.write(self.style.WARNING(f'    ⚠️  Multiple sites linked: {list(app.sites.values_list("domain", flat=True))}'))
        
        # Final recommendation
        self.stdout.write(self.style.SUCCESS('\n=== Recommendations ==='))
        
        google_apps = SocialApp.objects.filter(provider='google')
        if google_apps.count() > 1:
            self.stdout.write(self.style.ERROR('Fix duplicate Google apps:'))
            self.stdout.write('  1. Delete extra apps in Django admin')
            self.stdout.write('  2. Or run: python manage.py fix_google_oauth')
        elif google_apps.count() == 0:
            self.stdout.write(self.style.WARNING('Setup Google OAuth:'))
            self.stdout.write('  Run: python manage.py setup_google_oauth')
        else:
            app = google_apps.first()
            if app.sites.count() == 0:
                self.stdout.write(self.style.ERROR('Link Google app to site:'))
                self.stdout.write('  Run: python manage.py setup_google_oauth')
            else:
                self.stdout.write(self.style.SUCCESS('✓ Configuration looks correct'))
                self.stdout.write('\nIf you still get MultipleObjectsReturned error:')
                self.stdout.write('  1. Clear browser cache')
                self.stdout.write('  2. Restart Django server')
                self.stdout.write('  3. Check settings.SITE_ID = 1')

