"""Canonical writer for late-minute concession (Rule 10).

Called by the discipline app. This function is the ONLY code path in
the codebase that writes AcademyLateClear from a discipline-side call.

Standards: Rule 10 (one canonical writer); Kleppmann DDIA Ch.7 (transactions);
ISO 9001 §8.5.1 (controlled production); ALCOA+ Original.
"""
from django.db import transaction
from django.utils import timezone


def clear_late_concession(student_id, date, minutes, source="", by=None):
    """Clear N minutes from a student's late record for a given date.

    Args:
        student_id: AcademyStudent PK
        date: datetime.date of the late record
        minutes: positive int, minutes to clear
        source: string tag for audit (e.g. "discipline:convert:40pts")
        by: optional User who triggered the write

    Returns: AcademyLateClear.pk, or None if nothing to clear.
    Raises: ValueError if no late record exists or minutes <= 0.
    """
    from academy.models import AcademyLate, AcademyLateClear

    if minutes <= 0:
        raise ValueError("minutes must be positive")

    with transaction.atomic():
        late = (AcademyLate.objects
                .select_for_update()
                .filter(student_id=student_id, date=date)
                .first())
        if not late:
            raise ValueError(f"no late record for student {student_id} on {date}")

        minutes_to_clear = min(int(minutes), late.remaining_minutes)
        if minutes_to_clear <= 0:
            return None

        clear = AcademyLateClear.objects.create(
            late=late,
            minutes_cleared=minutes_to_clear,
            method="SOCIAL",  # non-fine, non-voice clear
            points_spent=0,
            notes=f"Bridge: {source}"[:200],
            cleared_by=by,
        )
        # re-evaluate status
        late.refresh_from_db()
        late.recompute_status()
        return clear.pk
