from django.core.management.base import BaseCommand
from django.db import transaction
from exams.models import KnowledgeComponent, ModelPaper, AttemptLog
from exams.kc_firewall import sanctioned_context

class Command(BaseCommand):
    help = "Enforces the official subject list, deduplicates, and archives junk safely."

    def handle(self, *args, **options):
        KEEP_SUBJECTS = [
            'Urdu', 'English', 'Mathematics', 'Physics', 'Chemistry', 'Biology',
            'Computer Science', 'Tarjuma tul Quran', 'Islamiyat',
            'General Science', 'General Knowledge', 'Waqfiyat e Ama',
            'Civics', 'Islamiyat Optional', 'Economics'
        ]

        self.stdout.write("Starting subject cleanup...")

        with transaction.atomic():
            # 1. Ensure ALL 15 subjects exist, keeping only ONE active duplicate
            created_count = 0
            deduplicated_count = 0
            
            for subj in KEEP_SUBJECTS:
                matches = KnowledgeComponent.objects.filter(subject=subj).order_by('id')
                
                if matches.exists():
                    # Keep the first (oldest) one active
                    primary = matches.first()
                    if not primary.is_active:
                        # Bypass firewall for reactivation
                        with sanctioned_context("clean_subjects_command"):
                            primary.is_active = True
                            primary.save()
                    
                    # Deactivate any duplicate rows for this exact same subject
                    duplicates = matches.exclude(id=primary.id)
                    if duplicates.exists():
                        # .update() bypasses the pre_save signal/firewall naturally
                        deduplicated_count += duplicates.update(is_active=False)
                else:
                    # Create it if it doesn't exist
                    with sanctioned_context("clean_subjects_command"):
                        KnowledgeComponent.objects.create(
                            subject=subj,
                            code=subj[:10].upper().replace(' ', ''),
                            is_active=True
                        )
                    created_count += 1

            self.stdout.write(self.style.SUCCESS(f"✅ Verified {len(KEEP_SUBJECTS)} official subjects (Created {created_count} new)."))
            if deduplicated_count > 0:
                self.stdout.write(self.style.SUCCESS(f"✅ Deactivated {deduplicated_count} duplicate KCs."))

            # 2. Deactivate any other subjects (junk)
            junk_kcs = KnowledgeComponent.objects.exclude(subject__in=KEEP_SUBJECTS)
            updated_count = junk_kcs.update(is_active=False)
            self.stdout.write(self.style.SUCCESS(f"✅ Deactivated {updated_count} junk KCs."))

            # 3. Archive Junk ModelPapers safely
            archived_count = 0
            junk_papers = ModelPaper.objects.exclude(subject__in=KEEP_SUBJECTS).exclude(subject='[ARCHIVED]')
            for paper in junk_papers:
                if AttemptLog.objects.filter(question__paper=paper).exists():
                    continue
                try:
                    with sanctioned_context("clean_subjects_command"):
                        paper.subject = "[ARCHIVED]"
                        paper.save()
                    archived_count += 1
                except Exception:
                    pass
            
            self.stdout.write(self.style.SUCCESS(f"✅ Archived {archived_count} junk ModelPapers."))
            self.stdout.write(self.style.SUCCESS("🎉 Subject cleanup complete!"))
