from django.core.management.base import BaseCommand
import json
from exams.models import ModelQuestion
from exams.services.data_quality_gate import check_question
from exams.services.subject_normalizer import canonical_subject

class Command(BaseCommand):
    help = 'Exports garbage questions to a JSON file for bulk AI healing.'

    def handle(self, *args, **options):
        questions = ModelQuestion.objects.filter(superseded_at__isnull=True).select_related('paper')
        garbage_list = []
        
        for q in questions:
            result = check_question(q.question_text, q.model_answer)
            if not result['is_valid']:
                garbage_list.append({
                    'id': q.id,
                    'subject': canonical_subject(q.paper.subject) if q.paper else 'General',
                    'question_text': q.question_text,
                    'current_model_answer': q.model_answer,
                    'issues': [i['reason'] for i in result['issues']]
                })
                
        with open('garbage_export.json', 'w', encoding='utf-8') as f:
            json.dump(garbage_list, f, indent=2, ensure_ascii=False)
            
        self.stdout.write(self.style.SUCCESS(f"Exported {len(garbage_list)} garbage questions to garbage_export.json"))
