"""Cascade logic — diary + attempt -> trophies/mizan/badges."""
import logging
from django.db import transaction
from django.utils import timezone

logger = logging.getLogger(__name__)

def _models():
    from exams.models import Student, CreditEvent, Badge, BadgeAward
    from exams.models_trophy import TrophyEvent
    from exams.mizan_algorithm import recompute
    return (Student, CreditEvent, TrophyEvent, recompute, Badge, BadgeAward)

def on_attempt_saved(attempt):
    Student, CreditEvent, TrophyEvent, recompute, Badge, BadgeAward = _models()
    try:
        student = attempt.student
        question = attempt.question
        day = timezone.localdate(attempt.created_at)
        if not attempt.result_json: return

        is_bulk = getattr(attempt, "is_bulk", False)
        pace = student.daily_question_count or 1
        pct = attempt.percentage

        route_weight = pace if is_bulk else 1
        trophy_count = max(0, round((pct / 100.0) * route_weight))

        with transaction.atomic():
            if trophy_count > 0 and not (
                isinstance(attempt.result_json, dict)
                and attempt.result_json.get('assessment_mode')
            ):
                event_key = f"Q_COMPLETE:{student.id}:{question.id}"
                TrophyEvent.objects.get_or_create(
                    event_key=event_key,
                    defaults={
                        'student': student, 'date': day,
                        'reason': "QUESTION_COMPLETE", 'pace': pace,
                        'base_count': trophy_count, 'bonus_count': 0, 'count': trophy_count,
                        'source_dqc_id': None
                    }
                )
        try: recompute(student)
        except Exception as exc: logger.exception("recompute failed: %s", exc)
    except Exception as exc:
        logger.exception("on_attempt_saved failed: %s", exc)

def on_diary_saved(record, delta_stars):
    Student, CreditEvent, TrophyEvent, recompute, Badge, BadgeAward = _models()
    try:
        academy_student = record.student
        exam_student = Student.objects.filter(code=academy_student.linked_code, is_active=True).first()
        if not exam_student: return
        day = record.date
        stars = int(record.star_rating or 0)
        pace = exam_student.daily_question_count or 1
        
        pct = stars * 20
        trophy_count = max(0, round((pct / 100.0) * pace))

        with transaction.atomic():
            if trophy_count > 0:
                event_key = f"DIARY:{exam_student.id}:{day}:{record.subject}"
                TrophyEvent.objects.get_or_create(
                    event_key=event_key,
                    defaults={
                        "student": exam_student, "date": day,
                        "reason": f"DIARY_{(record.subject or 'GEN')[:13]}",
                        "pace": pace, "base_count": trophy_count, "bonus_count": 0, "count": trophy_count,
                    },
                )
        try: recompute(exam_student)
        except Exception as exc: logger.exception("recompute failed: %s", exc)
    except Exception as exc:
        logger.exception("on_diary_saved failed: %s", exc)
