"""Thin helpers around ``app.llm.adapters`` for provider call sites."""

from __future__ import annotations

from typing import Any

from app.llm.adapters.messages import to_anthropic_messages as _to_anthropic_messages
from app.llm.adapters.messages import to_gemini_contents
from app.llm.adapters.tools import (
    parse_anthropic_tool_use,
    parse_gemini_function_calls,
    to_anthropic_tools,
    to_gemini_tools,
)
from app.llm.types import ToolCallResult

__all__ = [
    "merge_anthropic_messages",
    "parse_anthropic_tool_calls",
    "parse_gemini_tool_calls",
    "to_anthropic_messages",
    "to_anthropic_tools",
    "to_gemini_contents",
    "to_gemini_function_declarations",
    "to_gemini_tools",
]


def to_anthropic_messages(
    messages: list[dict[str, Any]],
) -> tuple[str | None, list[dict[str, Any]]]:
    system, converted = _to_anthropic_messages(messages)
    return system, merge_anthropic_messages(converted)


def merge_anthropic_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Merge consecutive same-role turns (Anthropic requires alternation)."""
    if not messages:
        return []

    merged: list[dict[str, Any]] = []
    for message in messages:
        role = message.get("role")
        content = message.get("content")
        if merged and merged[-1].get("role") == role:
            prev = merged[-1]["content"]
            merged[-1]["content"] = _join_content(prev, content)
            continue
        merged.append({"role": role, "content": content})
    return merged


def parse_anthropic_tool_calls(content: Any) -> list[ToolCallResult]:
    return parse_anthropic_tool_use(content)


def parse_gemini_tool_calls(parts: Any) -> list[ToolCallResult]:
    return parse_gemini_function_calls(parts)


def to_gemini_function_declarations(
    tools: list[dict[str, Any]] | None,
) -> list[dict[str, Any]]:
    """Flatten ``to_gemini_tools`` into function_declaration dicts."""
    wrapped = to_gemini_tools(tools)
    if not wrapped:
        return []
    declarations: list[dict[str, Any]] = []
    for item in wrapped:
        declarations.extend(list(item.get("function_declarations") or []))
    return declarations


def _join_content(left: Any, right: Any) -> Any:
    if isinstance(left, str) and isinstance(right, str):
        return f"{left}\n\n{right}" if left and right else left or right
    if isinstance(left, list) and isinstance(right, list):
        return [*left, *right]
    if isinstance(left, list):
        if right is None or right == "":
            return left
        return [*left, {"type": "text", "text": str(right)}]
    if isinstance(right, list):
        if left is None or left == "":
            return right
        return [{"type": "text", "text": str(left)}, *right]
    return str(left or "") + ("\n\n" if left and right else "") + str(right or "")
