
ALIAS = {
    "emaildomain": "domain",
    "domainexact": "domain",
    "exact": "exact",
    "domain": "domain",
}


def _alg_key(a: str) -> str:
    a = (a or "").lower().replace("_", "")
    return ALIAS.get(a, a)


def classify_match_type(details, use_relations: bool = True):
    """
    Classify match type based on evidence.

    With use_relations=True (default):
    - 'exact_domain' if any domain detail has relation="EXACT"
    - 'subsidiary' if any domain detail has relation="FAMILY" with corroboration
    - Falls back to legacy algorithm-based classification

    Legacy mode (use_relations=False or no relations present):
    - 'exact_domain' if any Email/Website/Domain evidence is exact with score >= 0.95
    - 'variant' otherwise
    """
    has_exact_domain = False
    has_family_domain = False
    has_strong_corroboration = False

    for d in details or []:
        alg = _alg_key(d.get("algorithm"))
        sc = float(d.get("score") or 0.0)
        if sc > 1.0:
            sc /= 100.0

        # Check for typed domain relations (new approach)
        if use_relations and "relation" in d:
            relation = d.get("relation")
            if relation == "EXACT":
                has_exact_domain = True
            elif relation == "FAMILY":
                has_family_domain = True

        # Legacy classification
        src = (d.get("source_field") or d.get("source_column") or "").lower()
        ref = (d.get("reference_field") or d.get("reference_column") or "").lower()

        # Check for domain evidence the old way (fallback)
        if not use_relations or "relation" not in d:
            if (
                sc >= 0.95
                and (alg in ("domain", "exact"))
                and any(k in f"{src}->{ref}" for k in ("email", "website", "domain"))
            ):
                has_exact_domain = True

        # Check for strong corroboration (name or phone)
        if sc >= 0.85 and any(
            k in f"{src}->{ref}" for k in ("company", "name", "phone")
        ):
            has_strong_corroboration = True

    # Determine match type
    if has_exact_domain:
        return "exact_domain"
    elif has_family_domain and has_strong_corroboration:
        return "subsidiary"  # or "alias"
    else:
        return "variant"
