"""Sporting age: initial age plus one per completed game season.

Birth dates and historical v1 results are never shifted or rewritten.
"""
from django.utils import timezone

SEASON_AGE_POLICY = "ftg.player.season_age.v1"


def calendar_age(birth, observed_on):
    return observed_on.year - birth.year - ((observed_on.month, observed_on.day) < (birth.month, birth.day))


def sporting_age(player, observed_on=None):
    from training.models import PlayerSeasonAgingResult
    current = observed_on is None
    observed_on = observed_on or timezone.localdate()
    reference = player.age_reference_date
    base = calendar_age(player.date_of_birth, min(reference, observed_on))
    results = PlayerSeasonAgingResult.objects.filter(
        player_id=player.pk,
        evidence_payload__season_age_policy=SEASON_AGE_POLICY,
    )
    if not current:
        # Sporting years take effect when the completed-season result commits,
        # even when game seasons use compressed or future calendar dates.
        results = results.filter(created_at__date__lte=observed_on)
    return base + results.count()


def with_sporting_age(queryset):
    """Database equivalent for paginated discovery; avoid one age query per candidate."""
    from django.db.models import Case, Count, F, IntegerField, Q, Value, When
    from django.db.models.functions import ExtractYear, Least
    return queryset.annotate(
        scout_reference=Least(F("age_reference_date"),Value(timezone.localdate())),
    ).annotate(scout_age=(ExtractYear("scout_reference")-ExtractYear("date_of_birth")-
        Case(When(Q(scout_reference__month__lt=F("date_of_birth__month")) |
                  Q(scout_reference__month=F("date_of_birth__month"),scout_reference__day__lt=F("date_of_birth__day")),then=Value(1)),
             default=Value(0),output_field=IntegerField())+
        Count("season_aging_results",filter=Q(season_aging_results__evidence_payload__season_age_policy=SEASON_AGE_POLICY),distinct=True)))
