from __future__ import annotations

from pathlib import Path

from fastapi.testclient import TestClient

from beaver.interfaces.web.app import create_app
from beaver.services.agent_service import AgentService


def test_debug_chat_logs_group_events_by_run(tmp_path: Path) -> None:
    service = AgentService(workspace=tmp_path)
    loaded = service.create_loop().boot()
    manager = loaded.session_manager
    session_id = "web:debug"
    run_id = "run-debug"
    manager.ensure_session(session_id, source="web", title="Debug")
    manager.append_message(
        session_id,
        run_id=run_id,
        role="system",
        event_type="run_started",
        event_payload={
            "source": "web",
            "task_id": "task-1",
            "attempt_index": 1,
            "intent_agent_decision": {"choice": "create_task", "reason": "needs tools"},
        },
        content="hello",
        context_visible=False,
    )
    manager.append_message(
        session_id,
        run_id=run_id,
        role="system",
        event_type="intent_agent_decision_snapshotted",
        event_payload={"choice": "create_task", "reason": "needs tools"},
        content="create_task",
        context_visible=False,
    )
    manager.append_message(
        session_id,
        run_id=run_id,
        role="system",
        event_type="llm_request_snapshotted",
        event_payload={"messages": [{"role": "user", "content": "hello"}], "tools": []},
        content='{"messages":[{"role":"user","content":"hello"}],"tools":[]}',
        context_visible=False,
    )
    manager.append_message(
        session_id,
        run_id=run_id,
        role="user",
        event_type="user_message_added",
        content="hello",
    )
    manager.append_message(
        session_id,
        run_id=run_id,
        role="assistant",
        event_type="assistant_message_added",
        content="hi",
        finish_reason="stop",
    )

    app = create_app(service=service, manage_service_lifecycle=False)
    with TestClient(app) as client:
        response = client.get("/api/debug/chat-logs")

    assert response.status_code == 200
    sessions = response.json()["sessions"]
    run = sessions[0]["runs"][0]
    assert run["run_id"] == run_id
    assert run["intent_agent_choice"] == "create_task"
    assert run["user_input"] == "hello"
    assert [event["event_type"] for event in run["events"]] == [
        "run_started",
        "intent_agent_decision_snapshotted",
        "llm_request_snapshotted",
        "user_message_added",
        "assistant_message_added",
    ]
    assert run["events"][2]["event_payload"]["messages"][0]["content"] == "hello"
