"""Build attempt report context for the teacher's Book Review view.

Mirrors the context produced by views_student_pipeline.attempt_result()
but works from an AttemptLog instead of a Submission.
"""
from django.utils import timezone


def build_attempt_log_report_context(attempt):
    """Return the exact context dict expected by _attempt_report_body.html."""
    from exams.models import KnowledgeComponent, KCCard, AIJourneyStage

    student = attempt.student
    question = attempt.question
    result = attempt.result_json or {}

    # Clone dict (don't mutate ORM object)
    final_result = dict(result) if result else {}

    # Socratic ladder normalization (defensive fallback if missing)
    if 'socratic_ladder' not in final_result:
        ladders = final_result.get('ladders') or []
        steps = []
        for ladder in ladders:
            if isinstance(ladder, dict):
                steps.extend(ladder.get('steps', []))
        final_result['socratic_ladder'] = steps

    # KC lookup — question.kc, then question.kc_code
    kc_obj = None
    kc_card = None
    if question:
        kc_obj = getattr(question, 'kc', None)
        if not kc_obj:
            q_kc_code = getattr(question, 'kc_code', '') or ''
            if q_kc_code:
                kc_obj = KnowledgeComponent.objects.filter(code=q_kc_code).first()

    if kc_obj:
        kc_card = KCCard.objects.filter(student=student, kc=kc_obj).first()

    cls = str(student.student_class).strip().lower()
    is_9th = '9' in cls

    # Handwriting points
    hw_points = 0
    try:
        from discipline.models import ClassHomeworkRecord
        hw_recs = ClassHomeworkRecord.objects.filter(
            student__linked_code=student.code, subject=""
        ).order_by('-date')[:14]
        if not hw_recs.exists():
            hw_recs = ClassHomeworkRecord.objects.filter(
                student__code=student.code, subject=""
            ).order_by('-date')[:14]
        hw_points = (
            sum(5 for r in hw_recs if r.handwriting_en_done) +
            sum(5 for r in hw_recs if r.handwriting_ur_done)
        )
    except Exception:
        hw_points = 0

    # AI journey stage — use the attempt directly
    ai_stage = AIJourneyStage.objects.filter(attempt_log=attempt).first()

    return {
        'ai_stage': ai_stage,
        'result': final_result,
        'question': question,
        'is_9th': is_9th,
        'kc_obj': kc_obj,
        'kc_card': kc_card,
        'hw_points': hw_points,
        'roadblock_prompt': None,
        'ladder_roadblock_prompt': None,
        'keyterms_roadblock_prompt': None,
        'story_roadblock_prompt': None,
        'field_name': 'misconceptions',
    }
