"""Message format conversion utilities.

Converts between different message formats (e.g., v2 chat messages to
OpenAI Responses API format).
"""


def map_to_responses_api(item: dict) -> dict:
    """Map a v2 chat message to OpenAI Responses API format.

    Handles three cases:
    - Messages with tool_calls -> function_call format
    - Tool role messages -> function_call_output format
    - Everything else -> pass through
    """
    if "tool_calls" in item:
        if not item["tool_calls"]:
            return item

        output = [{
            'type': 'function_call',
            'status': 'completed'
        }] * len(item["tool_calls"])

        for i, tool_call in enumerate(item["tool_calls"]):
            output[i]['arguments'] = tool_call['function']['arguments']
            output[i]['name'] = "rag" if tool_call['function']['name'] == "retriever" else tool_call['function']['name']
            output[i]['call_id'] = tool_call['id']
        return output[0]

    elif "role" in item:
        if item["role"] == "tool":
            output = {"type": "function_call_output"}
            output["call_id"] = item["tool_call_id"]
            output["output"] = str([item["content"], item["metadata"]])
            return output

    return item


def clean_output(serializable_output: list) -> list:
    """Transform raw agent output into frontend-friendly format.

    Groups function_call and function_call_output items as `debugPre` before
    each assistant message. Returns a list of dicts with keys:
    `role`, `content`, and `debugPre` (list of tool call/result dicts).

    Args:
        serializable_output: List of output items from an agent
            (message dicts, function_call dicts, function_call_output dicts)

    Returns:
        List of frontend-ready message dicts.
    """
    output = []
    debugPre = []
    for _message in serializable_output:
        if _message.get("type") == "message":
            content = _message.get("content", "")
            if isinstance(content, list):
                content = content[0]["text"]
            output.append({
                "debugPre": debugPre,
                "role": _message.get("role", "assistant"),
                "content": content,
            })
            debugPre = []
        else:
            debugPre.append(_message)
    return output
