"""
ISO year-week helpers. Centralises the `year*100 + week` encoding and
the isocalendar plumbing scattered across the pipeline.
"""

from datetime import datetime, timedelta
from constants import YW_MULTIPLIER


def encode_yw(year: int, week: int) -> int:
    """Pack an ISO year/week into a single int: 202615 for 2026 CW15."""
    return int(year) * YW_MULTIPLIER + int(week)


def decode_yw(yw: int) -> tuple[int, int]:
    """Unpack encode_yw output back to (year, week)."""
    yw = int(yw)
    return yw // YW_MULTIPLIER, yw % YW_MULTIPLIER


def iso_yw(d) -> tuple[int, int]:
    """(iso_year, iso_week) for a datetime/Timestamp."""
    ic = d.isocalendar()
    # pandas Timestamp.isocalendar() returns a named tuple with .year/.week,
    # datetime.date.isocalendar() returns a tuple (year, week, weekday).
    return (ic[0], ic[1])


def weeks_between(start: datetime, end: datetime) -> list[tuple[int, int]]:
    """All (iso_year, iso_week) pairs from start date to end date inclusive."""
    out, seen = [], set()
    cur = start
    while cur <= end:
        yw = iso_yw(cur)
        if yw not in seen:
            seen.add(yw)
            out.append(yw)
        cur += timedelta(days=1)
    return out
