"""分层恢复：尾行完整链 + 更早行压缩为索引块。"""

from __future__ import annotations

from aicd.agent.chat_context import (
    build_hydrated_messages,
    openai_message_list_valid,
    split_rows_for_recent_openai_suffix,
)
from aicd.db.store import ChatMessageRow


def _row(
    i: int,
    role: str,
    content: str,
    *,
    tool_calls_json: str | None = None,
    tool_call_id: str | None = None,
    tool_name: str | None = None,
) -> ChatMessageRow:
    return ChatMessageRow(
        id=i,
        session_id="s",
        role=role,
        content=content,
        tool_calls_json=tool_calls_json,
        created_at="",
        tool_call_id=tool_call_id,
        tool_name=tool_name,
    )


def test_split_prefers_valid_tool_suffix() -> None:
    rows = [
        _row(1, "user", "u1"),
        _row(2, "assistant", "", tool_calls_json='[{"id":"a","type":"function","function":{"name":"x","arguments":"{}"}}]'),
        _row(3, "tool", "{}", tool_call_id="a", tool_name="x"),
        _row(4, "user", "u2"),
    ]
    early, tail = split_rows_for_recent_openai_suffix(rows, prefer_tail_row_count=1)
    assert early == rows[:3]
    assert tail == [rows[3]]


def test_build_hydrated_inserts_compact_prefix() -> None:
    many_user = [_row(i, "user", f"msg{i}") for i in range(1, 12)]
    tail_chain = [
        _row(11, "user", "near"),
        _row(12, "assistant", "ok"),
    ]
    rows = many_user + tail_chain
    msgs = build_hydrated_messages(
        rows=rows,
        truncated_by_count=False,
        latest_summary=None,
        context_budget_tokens=500_000,
        recent_full_rows=2,
    )
    assert msgs[0]["role"] == "user"
    assert "较早聊天" in msgs[0]["content"]
    assert "#1 user" in msgs[0]["content"]
    assert openai_message_list_valid(msgs)
