"""
Source mapping configuration for historical complaint import.

Maps Excel 'جهة الشكوى' values to PXSource objects.
"""

from apps.px_sources.models import PXSource


SOURCE_CODE_MAP = {
    # Arabic sources
    "وزارة الصحة": "MOH",
    "مراجع": "PATIENT",
    "المراجع": "PATIENT",
    "ذوي المراجع": "FAMILY",
    "مجلس الضمان الصحي": "CHI",
    # English / code sources
    "moh": "MOH",
    "cchi": "CCHI",
    "chi": "CHI",
    "patients": "PATIENT",
    "patient": "PATIENT",
    "patient relatives": "FAMILY",
    "patient's relatives": "FAMILY",
    "family member": "FAMILY",
    "call center": "CALL-CENTER",
    "call-center": "CALL-CENTER",
    "staff": "STAFF",
    "survey": "SURVEY",
    "social media": "SOCIAL-MEDIA",
    "social-media": "SOCIAL-MEDIA",
    "public form": "PUBL-FORM",
    "insurance company": None,
    "شركة تأمين": None,
}


def resolve_px_source(source_value: str) -> "PXSource | None":
    """
    Resolve an Excel source string to a PXSource instance.

    Args:
        source_value: Value from the 'جهة الشكوى' column.

    Returns:
        PXSource instance or None if unmapped/empty.
    """
    if not source_value:
        return None

    normalized = str(source_value).strip()
    if not normalized or normalized.replace(".", "", 1).isdigit():
        return None

    # Direct lookup (case-insensitive)
    code = SOURCE_CODE_MAP.get(normalized.lower())
    if code is None:
        # Try stripping trailing spaces and retry
        code = SOURCE_CODE_MAP.get(normalized.lower().strip())

    if code is None:
        return None

    if code == "":
        return None

    try:
        return PXSource.objects.get(code=code)
    except PXSource.DoesNotExist:
        return None


EXTERNAL_SOURCE_CODES = {"MOH", "CCHI", "CHI"}


def get_complaint_source_type(px_source) -> str:
    """
    Determine complaint_source_type based on PXSource.
    Only MOH/CHI/CCHI are external; everything else is internal.
    """
    if px_source and px_source.code in EXTERNAL_SOURCE_CODES:
        return "external"
    return "internal"
