import json
import logging
from django.utils import timezone

logger = logging.getLogger(__name__)

EXPERT_PANEL_PROMPT = """ROLE: You are an Expert Panel consisting of a Punjab Board Subject Expert, a Pedagogical Designer, and an AI Evaluator. 
Your task is to analyze a student's attempt at a question and generate the exact remediation/feedback required to move them to the next stage.

PUNJAB BOARD REALITY:
- If the student is weak (Score 0-3), provide a simplified explanation and generate a basic PRACTICE question.
- If the student is average (Score 4-7), provide targeted feedback and generate a standard PRACTICE question.
- If the student is strong (Score 8-10), set next_stage to VERIFY and provide a tough challenge question.

=== INPUT DATA ===
Question: {question_text}
Model Answer: {model_answer}
Student Answer: {student_answer}
Student Class: {student_class}
Score: {score}

=== OUTPUT CONTRACT ===
Return ONLY a valid JSON object, no markdown, no explanation. The JSON must strictly match this schema:
{{
    "feedback_roman_urdu": "<Short encouraging feedback in Roman Urdu explaining why they got this score>",
    "next_stage": "<STUDY | PRACTICE | VERIFY>",
    "generated_question": {{
        "text": "<New question text for the next stage based on the student's weakness>",
        "answer": "<Model answer for the new question>",
        "options": ["<Option A>", "<Option B>", "<Option C>", "<Option D>"]
    }}
}}
"""

def generate_next_stage(attempt_log):
    from exams.models import AIJourneyStage
    
    prompt = EXPERT_PANEL_PROMPT.format(
        question_text=attempt_log.question.question_text,
        model_answer=attempt_log.question.model_answer,
        student_answer=attempt_log.student_answer,
        student_class=attempt_log.student.student_class,
        score=attempt_log.score
    )

    # ── INDUSTRY STANDARD: REJECT SIMULATED RESPONSES ──
    from django.conf import settings
    if settings.DEBUG:
        raw_content = json.dumps({
            "feedback_roman_urdu": "DEBUG MODE: Simulated response.",
            "next_stage": "PRACTICE",
            "generated_question": {"text": "Simulated Q", "answer": "A", "options": []}
        })
    else:
        raise NotImplementedError("CRITICAL: Simulated AI response is disabled in production. Connect real API.")

    try:
        data = json.loads(raw_content)
        required_keys = ['feedback_roman_urdu', 'next_stage', 'generated_question']
        for key in required_keys:
            if key not in data:
                raise ValueError(f"Missing key: {key}")

        stage = AIJourneyStage.objects.create(
            student=attempt_log.student,
            attempt_log=attempt_log,
            feedback=data['feedback_roman_urdu'],
            next_stage_type=data['next_stage'],
            generated_question_text=data['generated_question']['text'],
            generated_model_answer=data['generated_question']['answer'],
            generated_options=data['generated_question'].get('options', []),
            raw_json=data
        )
        return stage

    except (json.JSONDecodeError, ValueError) as e:
        logger.error(f"AI Journey JSON Validation Failed: {e}")
        return None
