"""
Management command to find and remove duplicate Keywords records.
Duplicates are defined as records with the same (seed_keyword, site, sector) combination.
The unique_together constraint should prevent new duplicates, but this cleans up any existing ones.
"""

from django.core.management.base import BaseCommand
from django.db.models import Count
from igny8_core.modules.planner.models import Keywords


class Command(BaseCommand):
    help = 'Find and remove duplicate Keywords records (same seed_keyword, site, sector)'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be deleted without actually deleting',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        
        if dry_run:
            self.stdout.write(self.style.WARNING('DRY RUN MODE - No records will be deleted'))
        
        # Find duplicates by grouping on (seed_keyword, site, sector)
        duplicates = (
            Keywords.objects
            .values('seed_keyword', 'site', 'sector')
            .annotate(count=Count('id'))
            .filter(count__gt=1)
            .order_by('-count')
        )
        
        total_duplicate_groups = duplicates.count()
        
        if total_duplicate_groups == 0:
            self.stdout.write(self.style.SUCCESS('✓ No duplicate records found. Database is clean.'))
            return
        
        self.stdout.write(
            self.style.WARNING(
                f'Found {total_duplicate_groups} duplicate group(s) (same seed_keyword, site, sector)'
            )
        )
        
        total_to_delete = 0
        deleted_count = 0
        
        for dup_group in duplicates:
            seed_keyword_id = dup_group['seed_keyword']
            site_id = dup_group['site']
            sector_id = dup_group['sector']
            count = dup_group['count']
            
            # Get all records in this duplicate group, ordered by created_at (keep the oldest)
            duplicate_records = Keywords.objects.filter(
                seed_keyword_id=seed_keyword_id,
                site_id=site_id,
                sector_id=sector_id
            ).order_by('created_at')
            
            # Keep the first (oldest) record, delete the rest
            records_to_delete = duplicate_records[1:]
            to_delete_count = records_to_delete.count()
            total_to_delete += to_delete_count
            
            # Get keyword text for display
            keyword_text = duplicate_records.first().keyword if duplicate_records.exists() else 'Unknown'
            
            self.stdout.write(
                f'  Group: seed_keyword={seed_keyword_id}, site={site_id}, sector={sector_id} '
                f'({count} records, will keep 1, delete {to_delete_count})'
            )
            self.stdout.write(f'    Keyword: "{keyword_text}"')
            
            if not dry_run:
                # Delete duplicates, keeping the oldest
                deleted = records_to_delete.delete()[0]
                deleted_count += deleted
                self.stdout.write(
                    self.style.SUCCESS(f'    ✓ Deleted {deleted} duplicate record(s)')
                )
            else:
                for record in records_to_delete:
                    self.stdout.write(
                        f'    Would delete: ID={record.id}, created={record.created_at}'
                    )
        
        if dry_run:
            self.stdout.write(
                self.style.WARNING(
                    f'\nDRY RUN: Would delete {total_to_delete} duplicate record(s)'
                )
            )
            self.stdout.write('Run without --dry-run to actually delete these records.')
        else:
            self.stdout.write(
                self.style.SUCCESS(
                    f'\n✓ Successfully deleted {deleted_count} duplicate record(s)'
                )
            )
            
            # Verify no duplicates remain
            remaining_duplicates = (
                Keywords.objects
                .values('seed_keyword', 'site', 'sector')
                .annotate(count=Count('id'))
                .filter(count__gt=1)
                .count()
            )
            
            if remaining_duplicates == 0:
                self.stdout.write(self.style.SUCCESS('✓ Verified: No duplicates remain in database'))
            else:
                self.stdout.write(
                    self.style.WARNING(
                        f'⚠ Warning: {remaining_duplicates} duplicate group(s) still remain. '
                        'This may indicate a database constraint issue.'
                    )
                )

