"""Explanation helpers for retrieval confidence results."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any


def _format_age(value: timedelta) -> str:
    seconds = int(value.total_seconds())
    if seconds < 60:
        return f"{seconds} seconds ago"
    minutes = seconds // 60
    if minutes < 60:
        return f"{minutes} minutes ago"
    hours = minutes // 60
    if hours < 24:
        return f"{hours} hours ago"
    days = hours // 24
    return f"{days} days ago"


@dataclass(frozen=True)
class ExplanationPayload:
    vector_similarity: float
    graph_path: list[str] | None
    graph_hops: int | None
    trust_score: float
    freshness: str
    reasoning: str

    def to_dict(self) -> dict[str, Any]:
        return {
            "vector_similarity": self.vector_similarity,
            "graph_path": self.graph_path,
            "graph_hops": self.graph_hops,
            "trust_score": self.trust_score,
            "freshness": self.freshness,
            "reasoning": self.reasoning,
        }


def build_explanation(
    *,
    vector_similarity: float,
    graph_path: list[str] | None,
    trust_score: float,
    episode_timestamp: datetime,
    now: datetime | None = None,
) -> ExplanationPayload:
    reference = now or datetime.now()
    age = reference - episode_timestamp
    freshness = _format_age(age)
    graph_hops = len(graph_path) - 1 if graph_path else None
    reasoning_parts = [
        f"Semantic match {vector_similarity:.2f}.",
        f"Trust {trust_score:.2f}.",
        f"Retrieved {freshness}.",
    ]
    if graph_path:
        reasoning_parts.append(
            f"Graph path length {graph_hops} linking {graph_path[0]} → {graph_path[-1]}."
        )
    reasoning = " ".join(reasoning_parts)

    return ExplanationPayload(
        vector_similarity=vector_similarity,
        graph_path=graph_path,
        graph_hops=graph_hops,
        trust_score=trust_score,
        freshness=freshness,
        reasoning=reasoning,
    )
