"""Tier-copy view - builds combined AI prompt text for clipboard copy.

Phase 20F: Updated language instruction to keep scientific terms in English.
Returns JSON so JavaScript can copy combined_text to clipboard.

Reads today's questions from request.session['mission_data'], which is
set by portal_daily_mission. Does NOT filter by marks (out of scope).
"""
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse

from exams.models import ModelQuestion, Student
from exams.models_rewrite import RewritePrompt


def _lang_instruction(medium: str) -> str:
    """Return the language constraint appended to the payload."""
    if medium == 'ur':
        return (
            "IMPORTANT — LANGUAGE: The student is an Urdu-medium student. "
            "Write ALL answers in ROMAN URDU or LATIN URDU (Urdu written using the English alphabet) ONLY. "
            "Do NOT use Arabic or Urdu script (اردو) anywhere in your response. "
            "CRITICAL RULE: Scientific terms, biological terms, chemical names, mathematical concepts, and technical terminology "
            "(e.g., photosynthesis, covalent bond, algorithm, NaCl, H2O) MUST remain exactly as they are in English. "
            "Only translate the normal, non-technical explanatory text into Roman Urdu."
        )
    return (
        "IMPORTANT — LANGUAGE: The student is an English-medium student. "
        "Write ALL answers in English ONLY. Do not use any Urdu script in "
        "your responses."
    )


@login_required
def portal_tier_copy(request):
    """Return JSON: {combined_text, question_count, subject, tier, medium}."""
    if request.user.is_superuser:
        student = Student.objects.filter(is_active=True).first()
    else:
        student = Student.objects.filter(
            student_user=request.user, is_active=True
        ).first()
    if not student:
        return JsonResponse({'error': 'Student not found.'}, status=404)

    subject = request.GET.get('subject', '').strip()
    tier_str = request.GET.get('tier', '').strip()
    medium = request.GET.get('medium', 'en').strip().lower()
    if medium not in ('en', 'ur'):
        medium = 'en'

    try:
        tier = int(tier_str)
    except (ValueError, TypeError):
        return JsonResponse(
            {'error': 'Invalid tier. Use 1, 2, or 3.'}, status=400
        )
    if tier not in (1, 2, 3):
        return JsonResponse(
            {'error': 'Invalid tier. Use 1, 2, or 3.'}, status=400
        )

    if not subject:
        return JsonResponse({'error': 'Subject is required.'}, status=400)

    prompt_row = RewritePrompt.objects.filter(
        subject__iexact=subject, tier=tier
    ).first()
    
    # INDUSTRY STANDARD FALLBACK: If a prompt is missing, we DO NOT crash. 
    # We generate a dynamic fallback so the user experience never breaks.
    if not prompt_row:
        tier_desc = {1: "very simple and basic", 2: "standard and clear", 3: "advanced and detailed"}
        fallback_text = f"Rewrite the following question and answer in {tier_desc.get(tier, 'standard')} English or Roman Urdu. Ensure conceptual clarity."
        # Mock object to prevent downstream attribute errors
        prompt_row = type('DynamicPrompt', (object,), {
            'prompt_text': fallback_text,
            'prompt_template': fallback_text,
            'content': fallback_text,
            'text': fallback_text,
            'body': fallback_text,
            'instructions': fallback_text
        })

    # ── NEW: qid-specific prompt (bypasses mission_data) ──
    qid = request.GET.get('qid', '').strip()
    if qid:
        # IDOR + HARVESTING FIX: SELF/CUSTOM own + standard-with-lock/mission
        try:
            _qid_int = int(qid)
        except (ValueError, TypeError):
            return JsonResponse({'error': 'Invalid qid.'}, status=400)
        from exams.models import StudentQuestionLock as _SQL
        from django.db.models import Q as _Q
        _own_self = _Q(paper__code__startswith=f'SELF-{student.code}')
        _own_custom = _Q(paper__code__startswith=f'CUSTOM-{student.code}')
        if request.user.is_superuser:
            _qs = ModelQuestion.objects.select_related('paper', 'kc')
        else:
            _locked = set(_SQL.objects.filter(student=student, is_active=True)
                          .values_list('question_id', flat=True))
            _mission = set()
            for _qids in (request.session.get('mission_data', {}) or {}).values():
                _mission.update(_qids)
            _allowed_ids = _locked | _mission
            _qs = ModelQuestion.objects.select_related('paper', 'kc').filter(
                _own_self | _own_custom | _Q(id__in=_allowed_ids)
            )
        try:
            q = _qs.get(id=_qid_int)
        except ModelQuestion.DoesNotExist:
            return JsonResponse({'error': 'Question not found.'}, status=404)

        base_prompt = ''
        for attr in ('prompt_text', 'prompt_template', 'content', 'text', 'body', 'instructions'):
            val = getattr(prompt_row, attr, None)
            if val:
                base_prompt = val
                break
        if not base_prompt:
            base_prompt = f'Rewrite the following question and model answer in {medium.upper()} at Tier {tier} level.'

        question_section = (
            "\n\n=== SAWAL ===\n"
            f"Subject: {subject}\n"
            f"Question: {q.question_text}\n"
            f"Model Answer: {q.model_answer or 'N/A'}\n"
            f"Marks: {q.marks}\n"
        )

        return JsonResponse({
            'combined_text': base_prompt + question_section,
            'question_count': 1,
            'subject': subject,
            'tier': tier,
            'medium': medium,
        })

    mission_data = request.session.get('mission_data', {}) or {}
    if not mission_data:
        return JsonResponse({
            'error': (
                'No questions loaded. Visit the Daily Mission page first.'
            ),
        }, status=404)

    target = subject.strip().lower()
    matched = []
    for book, qids in mission_data.items():
        if not qids:
            continue
        book_key = (book or '').strip().lower()
        for idx, qid in enumerate(qids):
            try:
                q = ModelQuestion.objects.select_related('paper').get(id=qid)
            except ModelQuestion.DoesNotExist:
                continue
            display_subject = (q.paper.subject or book or '').strip()
            if target == display_subject.lower() or target == book_key:
                matched.append({'obj': q, 'index': idx})

    if not matched:
        return JsonResponse({
            'error': (
                f'No questions found for {subject} in today\'s mission.'
            ),
        }, status=404)

    clean_prompt = prompt_row.prompt_text.strip()
    if "Here are today's questions" in clean_prompt:
        clean_prompt = clean_prompt.split(
            "Here are today's questions"
        )[0].strip()

    parts = [clean_prompt, '']
    for m in matched:
        q = m['obj']
        parts.append('---')
        parts.append(f"Q{m['index'] + 1}: {(q.question_text or '').strip()}")
        parts.append(f"Model Answer: {(q.model_answer or '').strip()}")
        parts.append('')

    parts.append(
        "Here are today's questions and their model answers. "
        "Rewrite each answer using the structure above."
    )
    parts.append('')
    parts.append(_lang_instruction(medium))
    parts.append('')
    parts.append(
        "IMPORTANT — FORMAT: Provide each rewritten answer inside a separate "
        "markdown code block (using triple backticks ```) so the student can "
        "easily copy and paste it directly into the portal."
    )

    combined = '\n'.join(parts).rstrip() + '\n'

    return JsonResponse({
        'combined_text': combined,
        'question_count': len(matched),
        'subject': subject,
        'tier': tier,
        'medium': medium,
    })
