from django.core.management.base import BaseCommand
import json
from exams.models import ModelQuestion

class Command(BaseCommand):
    help = 'Imports healed data from healed_import.json and updates the database.'

    def handle(self, *args, **options):
        try:
            with open('healed_import.json', 'r', encoding='utf-8') as f:
                healed_data = json.load(f)
        except FileNotFoundError:
            self.stdout.write(self.style.ERROR("healed_import.json not found!"))
            return
            
        updated_count = 0
        for item in healed_data:
            try:
                q = ModelQuestion.objects.get(id=item['id'])
                
                # Only update if AI provided valid text
                if item.get('question_text') and len(item['question_text']) > 10:
                    q.question_text = item['question_text']
                if item.get('model_answer') and len(item['model_answer']) > 5:
                    q.model_answer = item['model_answer']
                    
                q.save()
                updated_count += 1
            except ModelQuestion.DoesNotExist:
                pass
                
        self.stdout.write(self.style.SUCCESS(f"Successfully healed and updated {updated_count} questions in the database."))
