"""
Game economy signals — award/spend points on pipeline events.

Fires on:
  - AttemptLog post_save (created): awards ATTEMPT_PASS (+10) or ATTEMPT_FAIL (-5)
  - StudentQuestionLock post_save (created, active): awards STUDY_COMPLETE (+5)

All awards go through exams.services.points_ledger (idempotent, SHA-256 keyed).
Wrapped in try/except so a points failure never breaks the underlying save.

Standards: append-only ledger, idempotency, failure isolation (NIST SI-10).
"""
import logging
from django.db.models.signals import post_save
from django.dispatch import receiver

logger = logging.getLogger(__name__)


@receiver(post_save, sender='exams.AttemptLog')
def award_attempt_points(sender, instance, created, **kwargs):
    if not created:
        return
    if not instance.result_json:
        return  # Not yet graded
    from exams.services import points_ledger
    try:
        if instance.passed:
            points_ledger.award(
                student=instance.student,
                points=10,
                reason=f'Passed attempt on Q{instance.question_id}',
                code='ATTEMPT_PASS',
                evidence={'qid': instance.question_id, 'attempt_id': instance.id},
            )
        else:
            points_ledger.penalize(
                student=instance.student,
                points=5,
                reason=f'Failed attempt on Q{instance.question_id}',
                code='ATTEMPT_FAIL',
                evidence={'qid': instance.question_id, 'attempt_id': instance.id},
            )
    except Exception as exc:
        logger.exception("Attempt point award failed for attempt %s: %s",
                         instance.id, exc)


# DISABLED 2026-11-11: Blind STUDY_COMPLETE awards removed
# @receiver(post_save, sender='exams.StudentQuestionLock')
def award_study_points(sender, instance, created, **kwargs):
    return  # DISABLED 2026-11-11
    if not created:
        return
    if not instance.is_active:
        return
    from exams.services import points_ledger
    try:
        points_ledger.award(
            student=instance.student,
            points=5,
            reason=f'Study complete for Q{instance.question_id}',
            code='STUDY_COMPLETE',
            evidence={'qid': instance.question_id},
        )
    except Exception as exc:
        logger.exception("Study point award failed for lock %s: %s",
                         instance.id, exc)


@receiver(post_save, sender='exams.RPSItem')
def capture_on_graduation(sender, instance, created, **kwargs):
    """When an RPSItem reaches GRADUATED, ensure the student has that KC's KCCard."""
    if instance.mastery_state != 'GRADUATED':
        return
    from game.services import capture as capture_service
    try:
        capture_service.capture_creature(
            student=instance.student,
            kc_code=instance.kc_code,
            source='RPS_GRADUATED',
        )
    except Exception as exc:
        logger.exception("Capture on graduation failed for rps_item %s: %s",
                         instance.id, exc)
