import re
from django.core.management.base import BaseCommand
from exams.models import ModelQuestion
import latex2mathml.converter

class Command(BaseCommand):
    help = 'Pre-renders LaTeX math into MathML in the database (One-time fix)'

    def handle(self, *args, **kwargs):
        self.stdout.write("Scanning database for LaTeX to pre-render...")
        
        # FIX: Search for single backslash \( instead of double \\
        questions = ModelQuestion.objects.filter(
            question_text__contains='\\('
        ) | ModelQuestion.objects.filter(
            model_answer__contains='\\('
        )
        
        # Distinct to avoid duplicates
        questions = questions.distinct()
        self.stdout.write(f"Found {questions.count()} questions/answers with LaTeX.")

        updated_count = 0
        for q in questions:
            changed = False
            
            def convert_math(text):
                if not text: return text
                def replace_latex(match):
                    latex_code = match.group(1)
                    try:
                        return latex2mathml.converter.convert(latex_code)
                    except Exception:
                        return match.group(0)
                # FIX: Match single backslash \( ... \)
                return re.sub(r'\\\((.*?)\\\)', replace_latex, text)

            new_q_text = convert_math(q.question_text)
            if new_q_text != q.question_text:
                q.question_text = new_q_text
                changed = True

            new_a_text = convert_math(q.model_answer)
            if new_a_text != q.model_answer:
                q.model_answer = new_a_text
                changed = True

            if changed:
                q.save(update_fields=['question_text', 'model_answer'])
                updated_count += 1

        self.stdout.write(self.style.SUCCESS(f"✅ Successfully pre-rendered {updated_count} questions and solutions into MathML."))
