from ..exceptions import LLMGenerationError
from ..prompts import reply_system_prompt
from ..providers.factory import get_provider
from ..schemas import ChatMessage, SuggestResponseRequest


def _to_alternating_messages(history: list[ChatMessage]) -> list[dict]:
    """Collapse consecutive same-role turns into one message.

    OpenAI tolerates back-to-back "user" messages in the list; Anthropic's Messages
    API rejects them outright (it requires strict user/assistant alternation). Since
    conversation_history is built from an external source (an inbox thread) rather
    than turn-by-turn by this service, it can't be assumed to already alternate -
    merging here keeps every provider implementation equally usable instead of only
    working by accident with whichever one tolerates the input.
    """
    merged: list[dict] = []
    for message in history:
        content = f"[{message.timestamp}] {message.content}" if message.timestamp else message.content
        if merged and merged[-1]["role"] == message.role:
            merged[-1]["content"] += "\n" + content
        else:
            merged.append({"role": message.role, "content": content})
    return merged


def suggest_response(payload: SuggestResponseRequest) -> dict:
    system_prompt = reply_system_prompt(
        trip_context=payload.trip_context,
        num_suggestions=payload.num_suggestions,
    )
    messages = _to_alternating_messages(payload.conversation_history)

    try:
        return get_provider().complete_json(system_prompt, messages)
    except Exception as exc:
        raise LLMGenerationError("Failed to suggest a response", str(exc)) from exc
