"""WRA dated reference calculations, with monthly early rights.

Sections 45(1),(2),(4) and 46(1),(3), consolidated 9 August 2025.
The calendar-year ledger is distinct from service anniversary entitlements.
"""
from datetime import date
import calendar


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


def entitlement_reference(start: date | None, as_of: date,
                          attendance: str = 'unknown') -> tuple[float, float, str]:
    if start is None:
        return 0.0, 0.0, 'Date de service continu à confirmer par RH'
    if as_of < start:
        return 0.0, 0.0, 'Service non commencé à cette date'
    six, twelve = add_months(start, 6), add_months(start, 12)
    if as_of >= twelve:
        return 22.0, 15.0, (
            '12 mois de service atteints : référence 20 j annuels + 2 j additionnels '
            '/ 15 j sick par période applicable. Affectation au registre annuel à valider par RH.')
    if as_of < six:
        return 2.0, 0.0, (
            f'Acquisition anticipée à partir du {six:%d/%m/%Y}, sous condition de présence. '
            'Les 2 jours additionnels annuels restent à traiter séparément.')
    if attendance != 'confirmed':
        label = ('Présence intégrale non remplie' if attendance == 'not_met'
                 else 'Une absence sur les six premiers mois empêche ou suspend l’ouverture automatique')
        return 2.0, 0.0, (
            f'{label} : acquisition anticipée non attribuée. '
            f'12 mois atteints le {twelve:%d/%m/%Y}. Les 2 jours additionnels restent distincts.')
    # One credit in each subsequent service month (months 7 through 12).
    months = sum(add_months(start, n) <= as_of for n in range(6, 12))
    return float(months + 2), float(months), (
        f'Historique sans absence bloquante : {months} j anticipés annuels '
        f'/ {months} j sick à cette date, plus 2 j additionnels annuels. '
        'Droits pris en compte automatiquement ; reports gérés séparément par RH.')
