from ccma.domain.dates import DateValidationError, validate_member_dates
from ccma.domain.models import HOUSEKEEPER_MEMBER_FIELD_LABELS
from ccma.rules.api import RuleContext, task

RULE_ID = "birthdate-check"
ORDER = 10


def evaluate(context: RuleContext):
    member = context.member
    actions = []
    optional_fields = set(getattr(context.settings, "optional_member_fields", ()))
    for field, label in HOUSEKEEPER_MEMBER_FIELD_LABELS.items():
        if field in optional_fields:
            continue
        if str(getattr(member, field, "")).strip():
            continue
        code = "missing_birth_date" if field == "birth_date" else f"missing_member_field:{field}"
        detail = (
            "Das Geburtsdatum muss in der Mitgliederakte ergänzt werden."
            if field == "birth_date"
            else f"Das Feld {label} muss in der Mitgliederakte ergänzt werden."
        )
        actions.append(
            task(
                rule_id=RULE_ID,
                member=member,
                key_suffix=f"missing:{field}",
                severity="warning",
                title=f"{member.display_name}: {label} fehlt",
                detail=detail,
                code=code,
            )
        )
    try:
        validate_member_dates(
            birth_date=member.birth_date,
            accepted_at=member.accepted_at,
            membership_started_at=member.membership_started_at,
            membership_ended_at=member.membership_ended_at,
            today=context.today,
        )
    except DateValidationError as exc:
        actions.append(
            task(
                rule_id=RULE_ID,
                member=member,
                key_suffix="invalid",
                severity="error",
                title=f"{member.display_name}: Ungültige Datumsangabe",
                detail=str(exc),
                code="invalid_member_dates",
            )
        )
    return actions
