"""Tagging flow — orphan ModelQuestion KC assignment.

Mirrors game/translation_views.py::bulk_studio / bulk_save pattern.
Design: docs/algorithms/2026-10-20_tagging_flow.md
"""
import json
import logging
import re
from decimal import Decimal, InvalidOperation

from django.contrib.admin.views.decorators import staff_member_required
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from exams.models import KnowledgeComponent, ModelQuestion

logger = logging.getLogger(__name__)

ORPHAN_FILTER = {'kc__isnull': True, 'kc_code': ''}
MAX_BATCH = 40
MIN_BATCH = 5


def _subjects():
    return list(
        ModelQuestion.objects.filter(**ORPHAN_FILTER)
        .values_list('paper__subject', flat=True)
        .distinct()
        .order_by('paper__subject')
    )


def _progress(subject=None):
    qs = ModelQuestion.objects.all()
    if subject:
        qs = qs.filter(paper__subject=subject)
    total = qs.count()
    tagged = qs.exclude(**ORPHAN_FILTER).count()
    pct = int(tagged * 100 / total) if total else 0
    return tagged, total, pct


def _build_prompt(questions, kc_list, subject):
    kc_lines = [k.code + ' — ' + (k.title or '') for k in kc_list]
    q_lines = []
    for i, q in enumerate(questions, 1):
        text = (q.translated_question_text or q.question_text or '').replace('\n', ' ').strip()[:400]
        q_lines.append(str(i) + '. ' + text)

    return (
        'You are tagging Pakistani 9th-grade exam questions with KnowledgeComponent (KC) codes.\n\n'
        'Subject: ' + subject + '\n'
        'Available KCs (code — title):\n' + '\n'.join(kc_lines) + '\n\n'
        'TASK: For each question below, choose the single best KC code and output ONE line:\n'
        '<number>. <kc_code> | <confidence 0.0-1.0>\n\n'
        '- Use EXACTLY one of the KC codes above\n'
        '- If multiple fit, pick the most specific\n'
        '- Confidence: 0.9+ = obvious, 0.6-0.8 = good, 0.3-0.5 = forced best guess\n'
        '- NO explanations, NO preamble\n'
        '- Start your response immediately with "1."\n\n'
        'QUESTIONS (batch of ' + str(len(questions)) + ', ' + subject + '):\n\n'
        + '\n'.join(q_lines)
    )


@staff_member_required
def portal_teacher_orphans(request):
    subjects = _subjects()

    subject = request.GET.get('subject') or (subjects[0] if subjects else 'English')
    if subjects and subject not in subjects:
        subject = subjects[0]

    try:
        batch_size = int(request.GET.get('batch', MAX_BATCH))
    except (TypeError, ValueError):
        batch_size = MAX_BATCH
    batch_size = min(max(batch_size, MIN_BATCH), MAX_BATCH)

    questions = list(
        ModelQuestion.objects.filter(**ORPHAN_FILTER)
        .filter(paper__subject=subject)
        .order_by('id')[:batch_size]
    )

    kc_list = list(
        KnowledgeComponent.objects.filter(subject=subject)
        .exclude(code='KC-IMPORTED')
        .order_by('code')
    )

    bulk_prompt = _build_prompt(questions, kc_list, subject) if questions else ''

    sub_tagged, sub_total, sub_pct = _progress(subject)
    all_tagged, all_total, all_pct = _progress(None)

    return render(request, 'exams/portal_teacher_orphans.html', {
        'questions': questions,
        'kc_list': kc_list,
        'bulk_prompt': bulk_prompt,
        'batch_size': batch_size,
        'subject': subject,
        'subjects': subjects,
        'sub_tagged': sub_tagged,
        'sub_total': sub_total,
        'sub_pct': sub_pct,
        'all_tagged': all_tagged,
        'all_total': all_total,
        'all_pct': all_pct,
    })


_LINE_RE = re.compile(
    r'^\s*(\d+)\s*[.)\]:-]\s*([A-Za-z0-9_-]+)\s*(?:\|\s*([0-9.]+))?\s*$',
    re.MULTILINE,
)


def _parse_assignments(raw_text):
    text = re.sub(r'```[\w]*\n', '', raw_text or '')
    text = text.replace('```', '')

    results = []
    for m in _LINE_RE.finditer(text):
        n = int(m.group(1))
        code = m.group(2).strip()
        raw_conf = m.group(3)
        conf = 0.5
        if raw_conf:
            cleaned = raw_conf.rstrip('.')
            try:
                conf = float(cleaned)
            except ValueError:
                conf = 0.5
        conf = max(0.0, min(1.0, conf))
        results.append({'n': n, 'code': code, 'confidence': conf})
    return results


@csrf_exempt
@staff_member_required
@require_POST
def portal_teacher_orphans_save(request):
    try:
        data = json.loads(request.body)
    except json.JSONDecodeError:
        return JsonResponse({'status': 'error', 'message': 'Invalid JSON', 'saved': 0, 'failed': 0}, status=400)

    subject = (data.get('subject') or '').strip()
    batch_ids = data.get('batch_ids') or []
    raw_text = data.get('raw_text') or ''

    if not subject:
        return JsonResponse({'status': 'error', 'message': 'Missing subject', 'saved': 0, 'failed': 0}, status=400)
    if not batch_ids:
        return JsonResponse({'status': 'error', 'message': 'No batch_ids', 'saved': 0, 'failed': 0}, status=400)
    if not raw_text.strip():
        return JsonResponse({'status': 'error', 'message': 'No text pasted', 'saved': 0, 'failed': 0}, status=400)

    assignments = _parse_assignments(raw_text)
    if not assignments:
        return JsonResponse({
            'status': 'error',
            'message': 'Could not parse any "N. CODE | confidence" lines.',
            'saved': 0, 'failed': 0,
            'first_100_chars': raw_text[:100],
        }, status=400)

    by_n = {i + 1: qid for i, qid in enumerate(batch_ids)}

    valid = {
        k.code: k
        for k in KnowledgeComponent.objects.filter(subject=subject).exclude(code='KC-IMPORTED')
    }

    saved = 0
    failed = 0
    errors = []

    for a in assignments:
        qid = by_n.get(a['n'])
        if qid is None:
            failed += 1
            errors.append({'n': a['n'], 'reason': 'out of batch range'})
            continue
        kc = valid.get(a['code'])
        if kc is None:
            failed += 1
            errors.append({'n': a['n'], 'reason': 'unknown KC: ' + a['code']})
            continue
        try:
            q = ModelQuestion.objects.get(id=qid)
        except ModelQuestion.DoesNotExist:
            failed += 1
            errors.append({'n': a['n'], 'reason': 'question id not found'})
            continue

        q.kc_code = kc.code
        q.kc = kc
        try:
            q.match_score = Decimal(str(round(a['confidence'], 3)))
        except (InvalidOperation, ValueError):
            q.match_score = Decimal('0.5')
        q.match_status = 'auto'
        q.needs_teacher_review = True
        q.updated_at = timezone.now()
        q.updated_by = request.user
        q.save(update_fields=[
            'kc_code', 'kc', 'match_score', 'match_status',
            'needs_teacher_review', 'updated_at', 'updated_by',
        ])
        saved += 1

    logger.info('orphans_save subject=%s saved=%s failed=%s user=%s',
                subject, saved, failed, request.user.username)

    return JsonResponse({
        'status': 'success' if saved else 'error',
        'saved': saved,
        'failed': failed,
        'total_batch': len(batch_ids),
        'parsed': len(assignments),
        'errors': errors[:20],
    })
