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


class Command(BaseCommand):
    help = 'Fix duplicate Sites'

    def handle(self, *args, **options):
        self.stdout.write(self.style.SUCCESS('=== Fixing Sites ===\n'))
        
        # Get all sites
        sites = Site.objects.all()
        count = sites.count()
        
        self.stdout.write(f'Found {count} site(s)')
        
        if count > 1:
            # Keep Site with ID=1, delete others
            primary_site = Site.objects.get(id=1)
            self.stdout.write(f'Keeping: Site {primary_site.id} - {primary_site.domain}')
            
            # Delete other sites
            Site.objects.exclude(id=1).delete()
            self.stdout.write(self.style.SUCCESS('✓ Deleted duplicate sites'))
            
            # Update primary site
            primary_site.domain = '127.0.0.1:8000'
            primary_site.name = 'Tayapromediverse'
            primary_site.save()
            self.stdout.write(self.style.SUCCESS(f'✓ Updated primary site: {primary_site.domain}'))
            
        elif count == 1:
            site = sites.first()
            self.stdout.write(self.style.SUCCESS(f'✓ Only one site found (correct): {site.domain}'))
        else:
            # Create site
            site = Site.objects.create(
                id=1,
                domain='127.0.0.1:8000',
                name='Tayapromediverse'
            )
            self.stdout.write(self.style.SUCCESS(f'✓ Created site: {site.domain}'))
        
        self.stdout.write('\n=== Done ===')
        self.stdout.write('Your login and signup pages should work now!\n')

