"""Conversation history → LangChain message list (last-N window).

v1.0 keeps the last 20 messages verbatim; rolling summarisation of older
turns is deferred to v1.1 (see plan).
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .models import Conversation


HISTORY_WINDOW = 20


def build_history_messages(conversation: "Conversation") -> list:
    """Return a list of LangChain `HumanMessage` / `AIMessage` for prompt
    history. Excludes the message currently being processed (caller adds
    the latest user turn separately)."""
    from langchain_core.messages import AIMessage, HumanMessage

    qs = conversation.messages.order_by("-created_at")[:HISTORY_WINDOW]
    rows = list(qs)[::-1]  # chronological order
    out: list = []
    for m in rows:
        if m.role == "user":
            out.append(HumanMessage(content=m.content))
        elif m.role == "assistant":
            out.append(AIMessage(content=m.content))
        # tool/system roles deliberately skipped — handled inside the agent.
    return out
