"""
Helpers for resolving the academic year a mobile/web client is browsing.

Clients may pin a specific academic year (the "view as year X" switcher in the
app settings). The selection travels either as an `academic_year` query param
or as an `X-Academic-Year` header sent on every request. When neither is
present — or the id is invalid — we fall back to the currently active year.
"""

from django.utils import timezone

from .models import AcademicYear


def get_request_academic_year_id(request):
    """Return the academic year id the client asked for, or None."""
    year_id = None
    if hasattr(request, "query_params"):
        year_id = request.query_params.get("academic_year")
    if not year_id:
        year_id = request.headers.get("X-Academic-Year")
    try:
        return int(year_id) if year_id else None
    except (TypeError, ValueError):
        return None


def get_request_academic_year(request):
    """
    Return the AcademicYear the client is browsing: their explicit selection
    (header/query param) when valid, otherwise the active/current year.
    """
    year_id = get_request_academic_year_id(request)
    if year_id:
        year = AcademicYear.objects.filter(id=year_id).first()
        if year:
            return year

    return get_current_academic_year()


def get_current_academic_year():
    """
    Return the school's actual current academic year — ignoring any
    "view as year X" override the client may have pinned via the
    academic_year query param / X-Academic-Year header.

    Use this (instead of get_request_academic_year) for actions that only
    make sense in the present — creating a chat group, enrolling a student,
    etc. A client stuck on a stale pinned year (e.g. left over from browsing
    historical records and never reset) must not be able to act as if it
    were still that year.
    """
    today = timezone.now().date()
    return (
        AcademicYear.objects.filter(
            is_active=True, start_date__lte=today, end_date__gte=today
        ).first()
        or AcademicYear.objects.filter(is_active=True).first()
    )
