"""Master Plan Panel — reads StudentDayMission + AttemptLog + HealthEvent."""
import json
from collections import defaultdict
from datetime import timedelta

from django.utils import timezone
from django.db.models import Sum, Count, Q
from django.db.models.functions import TruncDate


EXPERT_SUBJECTS = [
    'English', 'Urdu', 'Mathematics', 'Science', 'Islamiat',
    'Social Studies', 'Computer', 'Islamiat Elective',
]


def _passing_failed_qids(student):
    from exams.models import AttemptLog
    passing, failed = set(), set()
    for al in AttemptLog.objects.filter(student=student, cancelled_at__isnull=True).values(
        'question_id', 'outcome', 'score', 'max_score'
    ):
        if al['outcome'] == 'CORRECT':
            passing.add(al['question_id'])
        elif al['max_score'] and (float(al['score']) / float(al['max_score'])) >= 0.80:
            passing.add(al['question_id'])
        else:
            failed.add(al['question_id'])
    failed -= passing
    return passing, failed


def get_missed_questions(student):
    from exams.models_day_mission import StudentDayMission
    passing, failed = _passing_failed_qids(student)
    result = {'done': defaultdict(list),
              'failed': defaultdict(list),
              'not_attempted': defaultdict(list)}

    for sdm in StudentDayMission.objects.filter(student=student).select_related(
        'question', 'question__paper'
    ):
        q = sdm.question
        item = {
            'qid': q.pk,
            'question_text': q.question_text or '',
            'model_answer': q.model_answer or '',
            'kc_code': q.kc_code or '',
            'marks': q.marks or 2,
            'subject': sdm.subject or 'General',
            'day': sdm.day_number,
        }
        if q.pk in passing:
            result['done'][item['subject']].append(item)
        elif q.pk in failed:
            result['failed'][item['subject']].append(item)
        else:
            result['not_attempted'][item['subject']].append(item)
    return result


def build_master_plan(student, daily_cap=20, per_subject_cap=5):
    """Today's plan. Failed items prioritized over not_attempted."""
    buckets = get_missed_questions(student)
    subject_counts = {}
    total_missed = 0
    for cat in ('failed', 'not_attempted'):
        for subj, items in buckets[cat].items():
            subject_counts[subj] = subject_counts.get(subj, 0) + len(items)
            total_missed += len(items)

    sorted_subjects = sorted(subject_counts.items(), key=lambda x: -x[1])
    plan, allocated = [], 0
    for subject, missed_count in sorted_subjects:
        if allocated >= daily_cap:
            break
        take_from = []
        for cat in ('failed', 'not_attempted'):
            take_from.extend(buckets[cat].get(subject, []))
        take = min(len(take_from), daily_cap - allocated, per_subject_cap)
        if take <= 0:
            continue
        plan.append({
            'subject': subject,
            'missed_count': missed_count,
            'daily_target': take,
            'questions': take_from[:take],
        })
        allocated += take
    return {'plan': plan, 'total_missed': total_missed, 'daily_target': allocated}




def get_expert_panel_status(student):
    """10 experts: 8 subject + handwriting + master auditor."""
    buckets = get_missed_questions(student)
    from exams.models import AttemptLog
    today = timezone.localdate()
    today_done = AttemptLog.objects.filter(
        student=student, created_at__date=today, outcome='CORRECT', cancelled_at__isnull=True
    ).count()

    experts = []
    for i, subject in enumerate(EXPERT_SUBJECTS):
        missed = sum(len(buckets[c].get(subject, []))
                     for c in ('failed', 'not_attempted'))
        done = len(buckets['done'].get(subject, []))
        if missed == 0:
            status, text = 'green', 'Caught up'
        elif missed <= 3:
            status, text = 'yellow', str(missed) + ' to review'
        else:
            status, text = 'red', str(missed) + ' missed'
        experts.append({
            'id': 'A' + str(i + 1), 'name': subject, 'role': 'subject',
            'missed': missed, 'done': done,
            'status': status, 'status_text': text,
        })

    experts.append({
        'id': 'A9', 'name': 'Handwriting', 'role': 'handwriting',
        'missed': 0, 'done': 0,
        'status': 'green', 'status_text': 'No pending work',
    })

    total_pending = sum(len(buckets[c][s])
                        for c in ('failed', 'not_attempted')
                        for s in buckets[c])
    auditor_status = 'green' if total_pending == 0 else (
        'yellow' if total_pending < 20 else 'red')
    experts.append({
        'id': 'A10', 'name': 'Master Auditor', 'role': 'master',
        'missed': total_pending, 'done': today_done,
        'status': auditor_status,
        'status_text': 'Auditing ' + str(len(EXPERT_SUBJECTS)) + ' experts',
    })
    return experts


def get_accuracy_trend(student, days=14):
    """Daily accuracy % from AttemptLog over last N days."""
    from exams.models import AttemptLog
    end = timezone.localdate()
    start = end - timedelta(days=days - 1)
    rows = (AttemptLog.objects
            .filter(student=student,
                    created_at__date__gte=start,
                    created_at__date__lte=end,
                    cancelled_at__isnull=True)
            .annotate(d=TruncDate('created_at'))
            .values('d')
            .annotate(total=Count('id'),
                      passed=Count('id', filter=Q(outcome='CORRECT')))
            .order_by('d'))
    by_date = {r['d']: (r['passed'], r['total']) for r in rows}
    labels, accuracy = [], []
    for i in range(days):
        d = start + timedelta(days=i)
        labels.append(d.strftime('%d %b'))
        p, t = by_date.get(d, (0, 0))
        accuracy.append(round((p / t) * 100, 1) if t else None)
    return {'labels': labels, 'accuracy': accuracy}


def get_mizan_trend(student, days=14):
    """Cumulative Mizan score reconstructed backward from HealthEvent."""
    from exams.models import HealthEvent, HealthScore
    hs = HealthScore.objects.filter(student=student).first()
    current_score = hs.score if hs else 500
    end = timezone.localdate()
    start = end - timedelta(days=days - 1)
    rows = (HealthEvent.objects
            .filter(student=student,
                    created_at__date__gte=start,
                    created_at__date__lte=end)
            .annotate(d=TruncDate('created_at'))
            .values('d')
            .annotate(total=Sum('points'))
            .order_by('d'))
    by_date = {r['d']: int(r['total'] or 0) for r in rows}
    opening = current_score - sum(by_date.values())
    labels, series = [], []
    running = opening
    for i in range(days):
        d = start + timedelta(days=i)
        labels.append(d.strftime('%d %b'))
        running += by_date.get(d, 0)
        series.append(running)
    return {'labels': labels, 'series': series, 'opening': opening}




def build_memorization_prompt(question, subject, tier=2):
    """Expert Panel builds a copy-paste prompt matching the player schema.
    Player reads: cfg.text, cfg.type, cfg.options, cfg.correct_answer, cfg.hint."""
    qtext = (question.question_text or '').strip()
    answer = (question.model_answer or '').strip()
    q_esc = qtext.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
    a_esc = answer.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
    tier_label = {1: 'Basic', 2: 'Standard', 3: 'Advanced'}.get(tier, 'Standard')

    return (
        "ROLE: You are a Punjab Board " + str(subject) + " curriculum designer "
        "building a step-by-step memorization flow for a Pakistani student ("
        + tier_label + " tier).\n\n"
        "QUESTION:\n" + qtext + "\n\n"
        "MODEL ANSWER:\n" + answer + "\n\n"
        "TASK: Return ONE JSON object with nodes and edges that teach the student to "
        "memorize this answer. The player reads cfg.text (question display), "
        "cfg.type, cfg.options, cfg.correct_answer, cfg.hint.\n\n"
        "REQUIRED JSON SHAPE (no markdown fences, no explanation):\n"
        "{\n"
        '  "nodes": [\n'
        '    {"id": 1, "type": "START", "label": "Begin", "config": {}},\n'
        '    {"id": 2, "type": "QUESTION", "label": "Read Q&A", "config": '
        '{"type": "mcq", "text": "READ CAREFULLY 3 TIMES:\\n\\nQUESTION:\\n' + q_esc + '\\n\\nMODEL ANSWER:\\n' + a_esc + '", '
        '"options": ["READY - I have read it"], "correct_answer": "READY - I have read it", "hint": "Just click READY"}},\n'
        '    {"id": 3, "type": "QUESTION", "label": "Keyword 1", "config": '
        '{"type": "mcq", "text": "Pick the correct word:\\n\\n<answer with keyword blanked>", '
        '"options": ["correct_word", "wrong1", "wrong2", "wrong3"], '
        '"correct_answer": "correct_word", "hint": "Starts with first letter, N letters"}},\n'
        '    ... one MCQ keyword node per keyword ...\n'
        '    {"id": 50, "type": "QUESTION", "label": "Sentence 1", "config": '
        '{"type": "fill_blank", "text": "Write the missing sentence:\\n\\n<answer with sentence blanked>", '
        '"correct_answer": "<exact sentence>", "hint": "Starts with..."}},\n'
        '    ... one fill_blank sentence node per sentence ...\n'
        '    {"id": 99, "type": "QUESTION", "label": "Full answer", "config": '
        '{"type": "fill_blank", "text": "Write the COMPLETE answer for:\\n\\n' + q_esc + '", '
        '"correct_answer": "' + a_esc + '", "hint": "Recall structure."}},\n'
        '    {"id": 100, "type": "END", "label": "Done", "config": {}}\n'
        "  ],\n"
        '  "edges": [\n'
        '    {"from": 1, "to": 2, "condition": "", "priority": 1},\n'
        '    ... sequential edges in node order ...\n'
        '    {"from": <q_id>, "to": <next_id>, "condition": "correct", "priority": 1},\n'
        '    {"from": <q_id>, "to": <q_id>, "condition": "wrong", "priority": 2}\n'
        "  ]\n"
        "}\n\n"
        "STRICT RULES:\n"
        "1. NODE TYPE QUESTION requires cfg.type of: mcq, true_false, fill_blank, reorder, or matching.\n"
        "2. READ node (id 2) is mcq with single option 'READY - I have read it'. correct_answer identical.\n"
        "3. Every keyword (word > 4 letters) gets its own MCQ node: blank the keyword in text with _____, "
        "options = [the keyword + 3 other long words from the answer as distractors], correct_answer = the keyword.\n"
        "4. Every sentence (> 20 chars) gets its own fill_blank node: blank the sentence in text with _____, "
        "correct_answer = the exact sentence (copy verbatim).\n"
        "5. Final node is fill_blank asking for the FULL model answer verbatim.\n"
        "6. Every QUESTION has TWO outgoing edges: correct -> next, wrong -> itself.\n"
        "7. Use ONLY node types: START, QUESTION, END.\n"
        "8. Output ONLY JSON. No markdown, no commentary.\n"
    )


def _build_mcq_distractors(answer, correct_kw, all_keywords):
    """Deterministic 3 distractors: other keywords from answer + generic fallback."""
    pool = [k for k in all_keywords if k.lower() != correct_kw.lower()]
    distractors = pool[:3]
    generic = ['concept', 'process', 'energy', 'system']
    gi = 0
    while len(distractors) < 3:
        distractors.append(generic[gi]); gi += 1
    return distractors[:3]


def get_or_create_memorization_flow(student, question, teacher_user=None):
    """Builds a research-backed flow: Gated Read -> Fill-in-Blanks -> Mastery Gate -> SM2 Grading."""
    from exams.models_flow import FlowDefinition, FlowNode, FlowEdge
    from exams.services.sm2_engine import get_due_keywords
    import json

    topic = (question.kc_code or '').strip() or ("Q" + str(question.pk))
    subject = getattr(getattr(question, 'paper', None), 'subject', '') or ''
    qtext = (question.question_text or '').strip()
    answer = (question.model_answer or '').strip()

    keywords, seen = [], set()
    for w in answer.split():
        wc = ''.join(c for c in w if c.isalnum() or c in "-'")
        if len(wc) > 4 and wc.lower() not in seen:
            seen.add(wc.lower()); keywords.append(wc)
    keywords = keywords[:8]

    due_keywords = get_due_keywords(student, question, keywords)

    flow = FlowDefinition.objects.create(
        title="Memorize Q" + str(question.pk),
        subject=subject, topic=topic,
        teacher=teacher_user, lesson_type='FLOW', status='PUBLISHED', is_published=True,
        mastery_threshold=90,
    )

    nodes_data = [
        {'type': 'START', 'label': 'Begin', 'config': {}},
        {'type': 'QUESTION', 'label': 'Pre-Train', 'config': {
            'type': 'fill_blank',
            'text': "Pre-Training:\n\nWithout looking, type the FIRST three words of the answer to:\n" + qtext,
            'correct_answer': ' '.join(answer.split()[:3]),
            'hint': "The first word starts with '" + answer[0] + "'.",
        }},
        {'type': 'QUESTION', 'label': 'Read', 'config': {
            'type': 'mcq',
            'text': "READ CAREFULLY (3 Times):\n\nQUESTION:\n" + qtext + "\n\nMODEL ANSWER:\n" + answer,
            'options': ['READY - I have read it'],
            'correct_answer': 'READY - I have read it',
            'hint': 'Just click READY.',
        }},
    ]

    for i, kw in enumerate(due_keywords, 1):
        nodes_data.append({'type': 'QUESTION', 'label': 'Keyword ' + str(i), 'config': {
            'type': 'fill_blank',
            'text': "Fill in the blank:\n\n" + answer.replace(kw, '_____', 1),
            'correct_answer': kw,
            'hint': "Starts with '" + kw[0] + "', " + str(len(kw)) + " letters.",
        }})
        nodes_data.append({'type': 'QUESTION', 'label': 'Hint ' + str(i), 'config': {
            'type': 'mcq',
            'text': "Oops! Let's review. The missing word starts with '" + kw[0] + "'.",
            'options': ['Try Again'],
            'correct_answer': 'Try Again',
            'hint': 'Click Try Again.'
        }})

    nodes_data.append({'type': 'QUESTION', 'label': 'Final Recall', 'config': {
        'type': 'fill_blank',
        'text': "Mastery Test:\n\nWrite the COMPLETE answer from memory for:\n" + qtext,
        'correct_answer': answer,
        'hint': 'Recall the full structure.',
    }})

    nodes_data.append({'type': 'QUESTION', 'label': 'Grading', 'config': {
        'type': 'mcq',
        'text': "How hard was this to remember? (This schedules your next review)",
        'options': ['Again (1)', 'Hard (3)', 'Good (4)', 'Easy (5)'],
        'correct_answer': 'Good (4)',
        'hint': 'Be honest.',
    }})

    nodes_data.append({'type': 'END', 'label': 'Done', 'config': {}})

    created = []
    for idx, n in enumerate(nodes_data):
        created.append(FlowNode.objects.create(
            flow=flow, node_type=n['type'], label=n['label'],
            position_x=150 + (idx % 4) * 280, position_y=100 + (idx // 4) * 180,
            config_json=json.dumps(n['config']),
        ))

    for i in range(len(created) - 1):
        src, tgt = created[i], created[i + 1]
        if src.node_type == 'QUESTION':
            if 'Hint' in src.label:
                FlowEdge.objects.create(flow=flow, source_node=src, target_node=created[i-1],
                                        label='return', priority=1, condition_json='{}')
            elif 'Keyword' in src.label:
                next_kw = created[i+2] if i+2 < len(created) else created[-1]
                FlowEdge.objects.create(flow=flow, source_node=src, target_node=next_kw,
                                        label='correct', priority=1, condition_json='{"if": "correct"}')
                FlowEdge.objects.create(flow=flow, source_node=src, target_node=tgt,
                                        label='wrong', priority=2, condition_json='{"if": "wrong"}')
            else:
                FlowEdge.objects.create(flow=flow, source_node=src, target_node=tgt,
                                        label='correct', priority=1, condition_json='{"if": "correct"}')
                FlowEdge.objects.create(flow=flow, source_node=src, target_node=src,
                                        label='wrong', priority=2, condition_json='{"if": "wrong"}')
        else:
            FlowEdge.objects.create(flow=flow, source_node=src, target_node=tgt,
                                    label='', priority=1, condition_json='{}')
    return flow, True
def build_memorization_prompt(question, subject, tier=2):
    qtext = (question.question_text or '').strip().replace('"', '\\"')
    answer = (question.model_answer or '').strip().replace('"', '\\"')
    tier_label = {1: 'Basic', 2: 'Standard', 3: 'Advanced'}.get(tier, 'Standard')

    return (
        "ROLE: You are a Punjab Board curriculum designer building a step-by-step memorization flow for a Pakistani student (" + tier_label + " tier).\n\n"
        "QUESTION:\n" + qtext + "\n\n"
        "MODEL ANSWER:\n" + answer + "\n\n"
        "TASK: Return ONE JSON object with nodes and edges that teach the student to memorize this answer.\n\n"
        "REQUIRED JSON SHAPE (no markdown, no explanation):\n"
        '{\n'
        '  "nodes": [\n'
        '    {"id": 1, "type": "START", "label": "Begin", "config": {}},\n'
        '    {"id": 2, "type": "QUESTION", "label": "Read", "config": {"type": "mcq", "text": "READ CAREFULLY 3 TIMES:\n\nQUESTION:\n' + qtext + '\n\nMODEL ANSWER:\n' + answer + '", "options": ["READY - I have read it"], "correct_answer": "READY - I have read it", "hint": "Just click READY"}},\n'
        '    {"id": 3, "type": "QUESTION", "label": "Keyword 1", "config": {"type": "fill_blank", "text": "Fill in the blank:\n\n<answer with keyword blanked>", "correct_answer": "<missing word>", "hint": "Starts with..."}},\n'
        '    ... one fill_blank node per keyword ...\n'
        '    {"id": 50, "type": "QUESTION", "label": "Final Recall", "config": {"type": "fill_blank", "text": "Write the COMPLETE answer for:\n\n' + qtext + '", "correct_answer": "' + answer + '", "hint": "Recall structure"}},\n'
        '    {"id": 51, "type": "END", "label": "Done", "config": {}}\n'
        '  ],\n'
        '  "edges": [\n'
        '    {"from": 1, "to": 2, "condition": "", "priority": 1},\n'
        '    {"from": 2, "to": 3, "condition": "correct", "priority": 1},\n'
        '    {"from": 2, "to": 2, "condition": "wrong", "priority": 2},\n'
        '    ... sequential edges for each keyword ...\n'
        '    {"from": <q_id>, "to": <next_id>, "condition": "correct", "priority": 1},\n'
        '    {"from": <q_id>, "to": <q_id>, "condition": "wrong", "priority": 2},\n'
        '    {"from": <last_q>, "to": 51, "condition": "correct", "priority": 1}\n'
        '  ]\n'
        '}\n\n'
        "STRICT RULES:\n"
        "1. Use 'text' field in config for the question prompt.\n"
        "2. FOR ALL KEYWORD AND RECALL NODES: you MUST use type 'fill_blank'. DO NOT use 'mcq' for keywords. Blank out ONE keyword with _____ in the text.\n"
        "3. Every QUESTION must have TWO outgoing edges: 'correct' to next, 'wrong' to itself.\n"
        "4. Use ONLY node types: START, QUESTION, END.\n"
        "5. Output ONLY JSON.\n"
    )
def build_memorization_prompt(question, subject, tier=2):
    """Expert Panel builds a copy-paste prompt enforcing the Sharjeel Akram Method."""
    qtext = (question.question_text or '').strip().replace('"', '\\"')
    answer = (question.model_answer or '').strip().replace('"', '\\"')
    
    # Fetch translated versions if available
    trans_q = getattr(question, 'translated_question_text', '') or ''
    trans_a = getattr(question, 'translated_model_answer', '') or ''
    trans_q = trans_q.strip().replace('"', '\\"')
    trans_a = trans_a.strip().replace('"', '\\"')
    
    bilingual_instruction = ""
    if trans_q or trans_a:
        bilingual_instruction = (
            "\nBILINGUAL REQUIREMENT: \n"
            "This student is studying in English/Urdu medium. You MUST add a Roman Urdu translation to the 'text' and 'correct_answer' fields in the JSON using the following translations:\n"
            "URDU QUESTION: " + trans_q + "\n"
            "URDU ANSWER: " + trans_a + "\n"
            "Format the text as: English Text \n \n Roman Urdu Translation\n"
        )

    return (
        "ROLE: You are a master educator building a learning pathway using the Sharjeel Akram Methodology.\n"
        "THE STUDE5T TO LEARN:\n"
        "SUBJECT: " + str(subject) + "\n"
        "QUESTION: " + qtext + "\n"
        "MODEL ANSWER: " + answer + "\n"
        + bilingual_instruction + "\n"
        "TASK: Return ONE JSON object for the flow engine.\n\n"
        "METHODOOGY CONSTRAINTS (DO NOT VIOLATE):\n"
        "1. GATED READ: The first node must be an MCQ with exactly one option: 'READY - I have read it'.\n"
        "2. CUED RECALL (FILL IN THE BLANK): All subsequent keyword nodes MUST use type 'fill_blank'. Blank out One keyword with _____ in the text.\n"
        "3. MASTERY GATE: Every fill_blank QUESTION must have TWO outgoing edges: 'correct' to the next node, and 'wrong' to itself (for retry).\n"
        "4. FINAL RECALL: The last node before 'END' must ask the student to type the FULL answer from memory.\n"
        "5. No additional text, no markdown, output ONLY valid JSON.\n\n"
        "REQUIRED JSON SHAPE\n"
        "{\n"
        '  "nodes": [\n'
        '    {"id": 1, "type": "START", "label": "Begin", "config": {}},\n'
        '    {"id": 2, "type": "QUESTION", "label": "Read", "config": {"type": "mcq", "text": "READ CAREFULLY DECLARY THIS:\n\n' + qtext + '\n\nANSWER:\n' + answer + '", "options": ["READY - I have read it"], "correct_answer": "READY - I have read it", "hint": "Click READY"}},\n'
        '    {"id": 3, "type": "QUESTION", "label": "Keyword 1", "config": {"type": "fill_blank", "text": "Fill in the blank:\n\n<answer with keyword blanked>", "correct_answer": "<missing word>", "hint": "Starts with..."}},\n'
        '    ... one fill_blank node per keyword ...\n'
        '    {"id": 50, "type": "QUESTION", "label": "Final Recall", "config": {"type": "fill_blank", "text": "Write the COMPLETE answer for:\n\n' + qtext + '", "correct_answer": "' + answer + '", "hint": "Recall structure"}},\n'
        '    {"id": 51, "type": "END", "label": "Done", "config": {}}\n'
        '  ],\n'
        '  "edges": [\n'
        '    {"from": 1, "to": 2, "condition": "", "priority": 1},\n'
        '    {"from": 2, "to": 3, "condition": "correct", "priority": 1},\n'
        '    {"from": 2, "to": 2, "condition": "wrong", "priority": 2},\n'
        '    ... sequential edges for each keyword ...\n'
        '    {"from": <q_id>, "to": <next_id>, "condition": "correct", "priority": 1},\n'
        '    {"from": <q_id>, "to": <q_id>, "condition": "wrong", "priority": 2},\n'
        '    {"from": <last_q>, "to": 51, "condition": "correct", "priority": 1}\n'
        '  ]\n'
        '}\n'
    )
