"""Response text and retrieval-telemetry extraction for evaluation."""

from typing import Any, Dict, Optional


def build_enhanced_response_from_eval_item(item: Dict[str, Any]) -> Dict[str, Any]:
    """Adapt a v1 eval item or turn to the scorer's response shape."""
    response = item.get("response", "")
    enhanced_response: Dict[str, Any] = {
        "raw_response_text": response,
        "display_response_text": response,
    }

    diagnostics = item.get("diagnostics")
    if isinstance(diagnostics, dict):
        executions = diagnostics.get("retrieval_executions")
        if isinstance(executions, list):
            enhanced_response["normalized_retrieval_telemetry"] = {
                "retrieval_executions": executions,
            }

    return enhanced_response


def get_response_text_for_evaluation(enhanced_response: Dict[str, Any]) -> str:
    """Extract plain text from an agent response dict for evaluation."""
    return enhanced_response.get("raw_response_text", "")


def get_retrieval_telemetry_for_evaluation(
    enhanced_response: Dict[str, Any],
) -> Optional[Dict[str, Any]]:
    """Return normalized retrieval telemetry from a captured or A2A response.

    Captured eval documents provide already-normalized telemetry through
    ``normalized_retrieval_telemetry``. A2A responses provide
    ``enhanced_response["retrieval_info"]`` (populated by the A2A client
    when the ``application/vnd.ms-workiq-internal.retrieval`` artifact is
    present) and runs it through
    :class:`custom_evaluators.retrieval.artifact_provider.RetrievalArtifactProvider`
    to produce the evaluator-facing ``retrieval_executions[]`` shape.

    Returns ``None`` when the response carries no retrieval artifact — this is
    the expected case for any A2A response from an agent that hasn't yet been
    upgraded to emit retrieval telemetry, and it lets retrieval evaluators
    surface ``error``/``retrieval_failure`` diagnostics rather than crashing.
    """
    normalized = enhanced_response.get("normalized_retrieval_telemetry")
    if isinstance(normalized, dict):
        return normalized

    raw = enhanced_response.get("retrieval_info")
    if raw is None:
        return None
    # Import lazily so the response_extractor doesn't pull in the retrieval
    # evaluator package at import time (keeps fast paths for tests that don't
    # exercise retrieval).
    from custom_evaluators.retrieval.artifact_provider import (
        RetrievalArtifactProvider,
    )
    return RetrievalArtifactProvider.normalize(raw)
