"""Single source of truth for student points.
Append-only via CreditEvent. Idempotent via SHA-256 evidence key.
Used by: stage skip, clue purchase, attendance redemption, pokemon rewards.
"""
import hashlib
from django.db.models import Sum
from exams.models import CreditEvent


def _idem_key(student, code, evidence_dict):
    payload = f"{student.id}:{code}:{str(sorted(evidence_dict.items()))}"
    return hashlib.sha256(payload.encode()).hexdigest()


def get_balance(student):
    """
    Returns the total spendable points for a student.
    Combines the unified CreditEvent ledger with the AcademyPoints wallet.
    """
    from django.db.models import Sum
    from exams.models import CreditEvent
    from academy.models import AcademyPoints
    
    # 1. Exam / Mizan Points
    exam_total = CreditEvent.objects.filter(student=student).aggregate(total=Sum('points'))['total'] or 0
    
    # 2. Discipline / Academy Points
    acad_obj = AcademyPoints.objects.filter(student__linked_code=student.code).first()
    disc_total = acad_obj.balance if acad_obj else 0
    
    # Return combined total
    return exam_total + disc_total

def can_afford(student, cost):
    return get_balance(student) >= cost



def _write_credit_event(student, points, reason, code, evidence, source):
    """Internal: single append-only CreditEvent write. Idempotent via SHA-256.

    Called exclusively by award(), spend(), penalize(), adjust().
    Do not call directly — use the public ledger functions.
    """
    evidence = evidence or {}
    idem = _idem_key(student, code, evidence)
    if CreditEvent.objects.filter(
        student=student, code=code, evidence__idem_key=idem,
    ).exists():
        return None
    return CreditEvent.objects.create(
        student=student, code=code, points=points, reason=reason,
        evidence={**evidence, 'idem_key': idem}, source=source,
    )


def award(student, points, reason, code='AWARD', evidence=None, source='AUTO'):
    """Positive award. Approval gate at 100 pts/hour."""
    from datetime import timedelta
    from django.utils import timezone
    from exams.models import CreditEvent, PendingPointAward
    points = abs(points)
    hour_ago = timezone.now() - timedelta(hours=1)
    recent = CreditEvent.objects.filter(student=student, created_at__gte=hour_ago, points__gt=0).aggregate(t=Sum('points'))['t'] or 0
    if points > 100 or (recent + points) > 100:
        return PendingPointAward.objects.create(student=student, points=points, code=code, reason=reason, evidence=evidence or {}, source=source, status='PENDING')
    return _write_credit_event(student, abs(points), reason, code, evidence, source)


def spend(student, points, reason, code='SPEND', evidence=None, source='AUTO'):
    """Deduct points. Idempotent. Raises ValueError if insufficient balance."""
    points = abs(points)
    if not can_afford(student, points):
        raise ValueError(
            f'Insufficient points: need {points}, have {get_balance(student)}'
        )
    return _write_credit_event(student, -points, reason, code, evidence, source)


def penalize(student, points, reason, code='PENALTY', evidence=None, source='AUTO'):
    """Deduct points even if insufficient balance (allows negative). Idempotent."""
    return _write_credit_event(student, -abs(points), reason, code, evidence, source)


def adjust(student, points, reason, code='ADJUST', evidence=None, source='AUTO'):
    """Signed point adjustment. Positive = grant, negative = deduct. Idempotent."""
    return _write_credit_event(student, points, reason, code, evidence, source)
