"""
Build the messages list for the Bedrock/Anthropic API from chat history.
"""

from sqlalchemy.orm import Session
from backend.models import Chat, Message

MAX_CONTEXT_CHARS = 400_000
MAX_MESSAGES = 80


def build_messages(chat: Chat, db: Session) -> list[dict]:
    rows: list[Message] = (
        db.query(Message)
        .filter(Message.chat_id == chat.id)
        .order_by(Message.created_at.desc())
        .limit(MAX_MESSAGES)
        .all()
    )
    rows.reverse()

    if not rows:
        return []

    total_chars = sum(len(m.content or "") for m in rows)
    idx = 0
    while total_chars > MAX_CONTEXT_CHARS and idx < len(rows) - 2:
        total_chars -= len(rows[idx].content or "")
        idx += 1

    trimmed = rows[idx:]

    while trimmed and trimmed[0].role != "user":
        trimmed = trimmed[1:]

    result: list[dict] = []
    for m in trimmed:
        content = m.content or ""
        if not content.strip():
            continue
        role = m.role
        if role not in ("user", "assistant"):
            continue
        if result and result[-1]["role"] == role:
            result[-1]["content"] += "\n" + content
        else:
            result.append({"role": role, "content": content})

    return result
