"""Explainability helpers for overlapping weighted features."""

from __future__ import annotations

from .types import FeatureMap


def _display_token(feature_key: str) -> str:
    """Strip internal feature prefixes to make explanation output readable."""
    parts = feature_key.split("::")
    if not parts:
        return feature_key
    if parts[0] in {"w", "g", "raw"} and len(parts) >= 3:
        return "::".join(parts[2:])
    if parts[0] == "fam" and len(parts) >= 2:
        return parts[1]
    return feature_key


def _sorted_overlap(
    feats_a: FeatureMap,
    feats_b: FeatureMap,
    prefix: str,
    top_k: int,
) -> list[tuple[str, float]]:
    """Return the top overlapping features for a given feature prefix."""
    out: list[tuple[str, float]] = []
    for key, wa in feats_a.items():
        if not key.startswith(prefix):
            continue
        wb = feats_b.get(key)
        if wb is None:
            continue
        contrib = float(min(abs(wa), abs(wb)))
        if contrib <= 0:
            continue
        out.append((_display_token(key), contrib))

    out.sort(key=lambda item: item[1], reverse=True)
    return out[:top_k]


def overlap_explain(
    features_a: FeatureMap,
    features_b: FeatureMap,
    score: float,
    profile: str,
    family: str,
    top_k: int = 10,
) -> dict:
    """Summarize overlap contributions between two encoded inputs."""
    top_k = max(0, int(top_k))
    return {
        "score": float(score),
        "top_word_overlaps": _sorted_overlap(features_a, features_b, prefix="w::", top_k=top_k),
        "top_ngram_overlaps": _sorted_overlap(features_a, features_b, prefix="g::", top_k=top_k),
        "profile": profile,
        "family": family,
    }
