from ccma.domain.dates import DateValidationError, validate_birth_date
from ccma.rules.api import RuleContext, task
from ccma.rules.scripts._shared import date_in_year, relative_title

RULE_ID = "birthday"
ORDER = 20


def evaluate(context: RuleContext):
    member = context.member
    if member.status == "ended":
        return []
    try:
        birth_date = validate_birth_date(member.birth_date, today=context.today)
    except DateValidationError:
        return []
    if not birth_date:
        return []
    occurrences = [
        date_in_year(birth_date, year) for year in range(context.today.year - 1, context.today.year + 2)
    ]
    occurrence = min(occurrences, key=lambda value: abs((value - context.today).days))
    delta = (occurrence - context.today).days
    if delta > context.settings.birthday_days_before or delta < -context.settings.birthday_days_after:
        return []
    age = occurrence.year - birth_date.year
    detail = f"Wird {age} Jahre alt." if delta >= 0 else f"Ist {age} Jahre alt geworden."
    return [
        task(
            rule_id=RULE_ID,
            member=member,
            key_suffix=str(occurrence.year),
            severity="info",
            title=relative_title(member.display_name, delta, "Geburtstag"),
            detail=detail,
            due_date=occurrence,
        )
    ]
