# students/utils.py  (add this to your existing utils.py or create it)
"""
Student ID generation — format: RB-YY-NNNN

Examples:
    RB-26-0001   first student admitted in 2026
    RB-26-0053   53rd student admitted in 2026
    RB-27-0001   first student admitted in 2027 (new cohort)

Logic:
    - YY  = last 2 digits of the admission year
    - NNNN = global sequence across ALL years, never resets
             (prevents any ID collision ever)
"""

from datetime import date


def generate_student_id(admission_year=None):
    """
    Generate the next available student ID in RB-YY-NNNN format.

    Args:
        admission_year: int (e.g. 2026). Defaults to current year.

    Returns:
        str  e.g. 'RB-26-0053'
    """
    from students.models import Student   # local import to avoid circular

    if admission_year is None:
        admission_year = date.today().year

    yy = str(admission_year)[-2:]   # '2026' -> '26'

    # Find the highest NNNN across ALL student IDs (not just this year)
    # so the sequence is always globally unique
    last = (
        Student.objects
        .filter(student_id__startswith='RB-')
        .order_by('-student_id')
        .values_list('student_id', flat=True)
        .first()
    )

    if last:
        try:
            # RB-26-0053 -> 53
            seq = int(last.split('-')[-1]) + 1
        except (ValueError, IndexError):
            seq = 1
    else:
        seq = 1

    return f'RB-{yy}-{seq:04d}'