"""services/payroll_cycle.py

The company's payroll cycle, as /api/v1/ai/leave/balance reports it:

    "payroll_cycle": {"type": "monthly", "start_date": "2026-09-01", "end_date": "2026-09-30"}
    "payroll_cycle": {"type": "custom",  "start_date": "2026-09-21", "end_date": "2026-10-20"}

type is "monthly" (a calendar month) or "custom" (a day of one month to the
day before it in the next — this tenant's 21st to the 20th). Both are one
month long; the same two types apply to every tenant.

It is the period a "per month" limit means — max_apply_in_month on the
regularization policy (HA-697 AC-05), and on the leave types — so a count of
requests "this month" uses these dates rather than a calendar month. This
tenant's cycle runs from the 21st to the 20th, which calendar arithmetic
would get wrong.

erp-api describes the CURRENT cycle only. A back-dated regularization can
fall in the previous one (the 20-day back window crosses the boundary), so
for both types the backend's window is stepped by whole months, keeping its
own start day: a 21 Sep – 20 Oct cycle has 21 Aug – 20 Sep before it. A type
erp-api adds later is not stepped — cycle_for() answers None rather than
guess its length.

Pure: no I/O, no imports from the rest of the app.
"""
from __future__ import annotations

import calendar
from dataclasses import dataclass
from datetime import date, datetime, timedelta
from typing import Optional

MONTHLY = "monthly"
CUSTOM = "custom"

#: Cycle types that are one month long, so stepping by whole months finds the
#: cycle before/after the one erp-api reported.
MONTH_LONG_TYPES = frozenset({MONTHLY, CUSTOM})

# How far cycle_for() will step from the current cycle. A regularization is
# at most a few weeks back; anything further means bad input, not a date to
# find a cycle for.
_MAX_STEPS = 24


@dataclass(frozen=True)
class PayrollCycle:
    type: str
    start: date
    end: date

    def contains(self, day: date) -> bool:
        return self.start <= day <= self.end

    def label(self) -> str:
        """"Sep 2026" for a cycle that is one calendar month, else
        "21 Aug – 20 Sep 2026" / "21 Dec 2026 – 20 Jan 2027"."""
        last_day = calendar.monthrange(self.start.year, self.start.month)[1]
        if (self.start.day == 1 and self.end.day == last_day
                and (self.start.year, self.start.month) == (self.end.year, self.end.month)):
            return self.start.strftime("%b %Y")
        if self.start.year == self.end.year:
            return f"{self.start.strftime('%d %b')} – {self.end.strftime('%d %b %Y')}"
        return f"{self.start.strftime('%d %b %Y')} – {self.end.strftime('%d %b %Y')}"

    def as_dict(self) -> dict:
        return {"type": self.type, "start_date": self.start.isoformat(),
                "end_date": self.end.isoformat(), "label": self.label()}


def _parse_day(value) -> Optional[date]:
    try:
        return datetime.strptime(str(value or "").strip()[:10], "%Y-%m-%d").date()
    except ValueError:
        return None


def from_balance_data(data) -> Optional[PayrollCycle]:
    """The cycle from a /leave/balance `data` block, or None when it is
    missing or malformed. Read from data.payroll_cycle, and from
    data.leave_settings.payroll_cycle in case erp-api nests it there."""
    if not isinstance(data, dict):
        return None
    raw = data.get("payroll_cycle")
    if not isinstance(raw, dict):
        raw = (data.get("leave_settings") or {}).get("payroll_cycle")
    if not isinstance(raw, dict):
        return None
    start, end = _parse_day(raw.get("start_date")), _parse_day(raw.get("end_date"))
    if start is None or end is None or end < start:
        return None
    return PayrollCycle(type=str(raw.get("type") or "").strip().lower(), start=start, end=end)


def _add_months(day: date, months: int) -> date:
    month_index = day.month - 1 + months
    year, month = day.year + month_index // 12, month_index % 12 + 1
    return date(year, month, min(day.day, calendar.monthrange(year, month)[1]))


def cycle_for(current: Optional[PayrollCycle], day: date) -> Optional[PayrollCycle]:
    """The cycle `day` falls in: `current` itself, or — for a month-long cycle —
    the one that many whole months before/after it. None when there is no
    current cycle, or its type isn't month-long and `day` is outside it."""
    if current is None:
        return None
    if current.contains(day):
        return current
    if current.type not in MONTH_LONG_TYPES:
        return None
    step = -1 if day < current.start else 1
    for n in range(1, _MAX_STEPS + 1):
        start = _add_months(current.start, step * n)
        end = _add_months(current.start, step * n + 1) - timedelta(days=1)
        candidate = PayrollCycle(type=current.type, start=start, end=end)
        if candidate.contains(day):
            return candidate
    return None
