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


class Command(BaseCommand):
    help = 'Check Sites and SocialApp configuration'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=== Sites Configuration ===\n'))
        
        # Check sites
        sites = Site.objects.all()
        self.stdout.write(f'Total sites: {sites.count()}')
        for site in sites:
            self.stdout.write(f'  Site {site.id}: {site.domain} - {site.name}')
        
        # Check Google OAuth apps
        self.stdout.write(self.style.SUCCESS('\n=== Google OAuth Configuration ===\n'))
        google_apps = SocialApp.objects.filter(provider='google')
        self.stdout.write(f'Total Google apps: {google_apps.count()}')
        
        for app in google_apps:
            self.stdout.write(f'  App ID {app.id}: {app.name}')
            self.stdout.write(f'    Client ID: {app.client_id}')
            self.stdout.write(f'    Sites: {[s.domain for s in app.sites.all()]}')
        
        # Check for issues
        self.stdout.write(self.style.SUCCESS('\n=== Issues Check ===\n'))
        
        if sites.count() > 1:
            self.stdout.write(self.style.WARNING(f'⚠️  Multiple sites found ({sites.count()}). This might cause issues.'))
            self.stdout.write('   Recommended: Keep only one site for local development.')
        
        if google_apps.count() > 1:
            self.stdout.write(self.style.ERROR(f'✗ Multiple Google OAuth apps found ({google_apps.count()})!'))
            self.stdout.write('   Run: python manage.py fix_google_oauth')
        elif google_apps.count() == 0:
            self.stdout.write(self.style.WARNING('⚠️  No Google OAuth app configured.'))
            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('✗ Google OAuth app has no sites linked!'))
                self.stdout.write('   Run: python manage.py setup_google_oauth')
            else:
                self.stdout.write(self.style.SUCCESS('✓ Google OAuth configuration looks correct'))

