"""Helpers to map LangGraph outputs to plain text."""

from __future__ import annotations

from typing import Any

from langchain_core.messages import AIMessage, BaseMessage


def _message_content_to_str(message: BaseMessage) -> str:
    content = message.content
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        parts: list[str] = []
        for block in content:
            if isinstance(block, str):
                parts.append(block)
            elif isinstance(block, dict) and "text" in block:
                parts.append(str(block["text"]))
        return "".join(parts)
    return str(content)


def langgraph_result_to_text(result: Any) -> str:
    """Extract user-visible text from a LangGraph invocation result.

    Prefers the last assistant (`AIMessage`) in a ``messages`` list; otherwise
    uses the last message or ``str(result)``.
    """
    if isinstance(result, dict) and "messages" in result:
        messages = result["messages"]
        if not messages:
            return ""
        for m in reversed(messages):
            if isinstance(m, AIMessage):
                return _message_content_to_str(m)
            if isinstance(m, dict) and m.get("role") == "assistant":
                c = m.get("content", "")
                return c if isinstance(c, str) else str(c)
        last = messages[-1]
        if isinstance(last, BaseMessage):
            return _message_content_to_str(last)
        return str(last)
    return str(result)
