"""Operations services — donor/partner lifecycle helpers.

PRD §5.1 FRFA-GPS007–009 — donor duplicate detection: before saving a new
Donor row, callers should call :func:`find_duplicate_donor` with the
prospective name + country; the UI surfaces a confirm-or-link dialog when a
match exists instead of silently creating a parallel row.
"""
from __future__ import annotations

from django.db.models import QuerySet

from apps.core.countries import to_country_name
from apps.rims.operations.models import Donor


def find_duplicate_donor(name: str, country: str = "") -> Donor | None:
    """Return the first Donor matching *name* (case-insensitive) and *country*
    (exact, case-insensitive when set, treat blank as wildcard).

    Case-insensitive name matching catches the common re-entry pattern
    ("ACME Foundation" vs "acme foundation"). Country narrows the match so
    two distinct national offices of the same donor don't collide.
    """
    name = (name or "").strip()
    if not name:
        return None
    qs: QuerySet[Donor] = Donor.objects.filter(name__iexact=name)
    country = to_country_name(country)
    if country:
        qs = qs.filter(country__iexact=country)
    return qs.first()
