"""Pure deterministic helpers for exact kickoff scheduling.

No Django imports live here so policy behavior can be unit-tested without ORM
bootstrapping. Datetimes passed into this module are expected to be aware.
"""
from __future__ import annotations

from datetime import date, datetime, time, timedelta
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

KICKOFF_POLICY_KEY = "ftg.match.kickoff_scheduling.v1"
KICKOFF_POLICY_VERSION = "1.0.0"
KICKOFF_SCHEMA_VERSION = 1


class KickoffSchedulingPolicyV1:
    policy_key = KICKOFF_POLICY_KEY
    policy_version = KICKOFF_POLICY_VERSION
    schema_version = KICKOFF_SCHEMA_VERSION

    # Prefer meaningful football-like shifts instead of tiny arbitrary moves.
    # The anchor date remains first; clashes then search nearby mid-week/weekend
    # alternatives in deterministic order.
    default_day_offsets = (0, 3, -3, 4, -4, 2, -2, 1, -1, 5, -5, 6, -6, 7, -7)

    @staticmethod
    def validate_timezone_name(value: str) -> str:
        value = (value or "").strip()
        if not value:
            raise ValueError("Timezone name is required.")
        try:
            ZoneInfo(value)
        except ZoneInfoNotFoundError as exc:
            raise ValueError(f"Unknown IANA timezone: {value}") from exc
        return value

    @classmethod
    def local_to_utc(cls, *, local_date: date, local_time: time, timezone_name: str) -> datetime:
        timezone_name = cls.validate_timezone_name(timezone_name)
        if local_time.tzinfo is not None:
            local_time = local_time.replace(tzinfo=None)
        local_value = datetime.combine(local_date, local_time, tzinfo=ZoneInfo(timezone_name))
        return local_value.astimezone(ZoneInfo("UTC"))

    @classmethod
    def candidate_dates(cls, *, anchor_date: date, season_start: date, season_end: date, max_shift_days: int):
        max_shift_days = max(0, int(max_shift_days))
        offsets = [offset for offset in cls.default_day_offsets if abs(offset) <= max_shift_days]
        # For configurations allowing a wider range, append deterministic
        # offsets not covered by the canonical football-oriented sequence.
        covered = set(offsets)
        for delta in range(1, max_shift_days + 1):
            for offset in (delta, -delta):
                if offset not in covered:
                    offsets.append(offset)
                    covered.add(offset)
        return tuple(
            candidate
            for candidate in (anchor_date + timedelta(days=offset) for offset in offsets)
            if season_start <= candidate <= season_end
        )

    @staticmethod
    def rest_window(*, kickoff: datetime, min_rest_hours: int) -> tuple[datetime, datetime]:
        delta = timedelta(hours=max(0, int(min_rest_hours)))
        return kickoff - delta, kickoff + delta
