"""Shared utility functions for agents."""
from typing import Any


def build_metrics_context(braintrust_client: Any | None, context_type: str = "optimizer") -> str:
    """
    Build a formatted metrics context string for agent system messages.

    Args:
        braintrust_client: The BraintrustClient instance (may be None)
        context_type: Type of context to build - "optimizer" or "analyzer"
                     This affects the wording of the context message

    Returns:
        A formatted string describing the key metrics with their configurations,
        or an empty string if no metrics are available.

    Note:
        All metric scores are normalized to "higher is better" at data ingestion time,
        so optimization_direction handling is not needed here.
    """
    if braintrust_client is None:
        return ""

    # Extract key_metrics and metrics_config_dict from client
    key_metrics = []
    metrics_config_dict = {}

    if getattr(braintrust_client, "key_metrics", None):
        key_metrics = [m for m in braintrust_client.key_metrics if isinstance(m, str)]

    if getattr(braintrust_client, "metrics_config_dict", None):
        metrics_config_dict = braintrust_client.metrics_config_dict

    if not key_metrics:
        return ""

    # Build detailed metrics information
    metrics_details = []
    for metric_name in key_metrics:
        metric_config = metrics_config_dict.get(metric_name, {})
        is_llm_judged = metric_config.get('is_llm_judged', True)
        description = metric_config.get('description', '')
        measurement_purpose = metric_config.get('measurement_purpose', '')

        metric_info = f"  - {metric_name}"
        if not is_llm_judged:
            metric_info += " (Rule-based metric)"
        if description:
            metric_info += f"\n    Description: {description}"
        if measurement_purpose:
            metric_info += f"\n    Purpose: {measurement_purpose}"

        metrics_details.append(metric_info)

    # Build the final context message based on context type
    # Note: All scores are already normalized to "higher is better"
    if context_type == "optimizer":
        key_metrics_note = (
            "Key Metrics Focus:\n"
            f"- Prioritize issues tied to these metrics (higher scores are better):\n"
            + "\n".join(metrics_details) + "\n"
            "- Ignore other metric mentions that are outside this list.\n\n"
        )
    elif context_type == "analyzer":
        key_metrics_note = (
            "Key Metrics Focus:\n"
            f"- ONLY focus on these metrics (higher scores are better):\n"
            + "\n".join(metrics_details) + "\n"
            "- Ignore other metric mentions in judge_response.\n\n"
        )
    else:
        # Default/generic context
        key_metrics_note = (
            "Key Metrics (higher scores are better):\n"
            + "\n".join(metrics_details) + "\n\n"
        )

    return key_metrics_note
