"""Calendar-aligned period windows — shared by every dashboard that offers a
monthly / quarterly / half-yearly / annual view (currently the TA dashboard's
summaries, and the Candidates page's `period=` drill-down filter), so a card's
count and its drill-down always use the identical window.

Moved out of apps.dashboard.ta_views (which still imports from here) so a
second consumer doesn't have to duplicate — and risk drifting from — the same
calendar math.
"""

from datetime import date

from django.utils import timezone

PERIODS = ("monthly", "quarterly", "half_yearly", "annually")


def period_window(period, today=None):
    """(start, end_exclusive, prev_start, prev_end_exclusive), calendar-aligned."""
    today = today or timezone.localdate()
    year = today.year
    if period == "quarterly":
        q = (today.month - 1) // 3
        start = date(year, q * 3 + 1, 1)
        prev_start = date(year - 1, 10, 1) if q == 0 else date(year, (q - 1) * 3 + 1, 1)
    elif period == "half_yearly":
        start = date(year, 1 if today.month <= 6 else 7, 1)
        prev_start = date(year - 1, 7, 1) if today.month <= 6 else date(year, 1, 1)
    elif period == "annually":
        start = date(year, 1, 1)
        prev_start = date(year - 1, 1, 1)
    else:  # monthly
        start = date(year, today.month, 1)
        prev_start = date(year - 1, 12, 1) if today.month == 1 else date(year, today.month - 1, 1)
    end = today  # end of current window = today (inclusive filtering below)
    return start, end, prev_start, start


def parse_period(request):
    period = (request.query_params.get("period") or "monthly").lower()
    return period if period in PERIODS else "monthly"
