from __future__ import annotations

from openkite.db import ChatHistoryStore


def test_db_roundtrip(tmp_path) -> None:
    db_path = tmp_path / "history.db"
    store = ChatHistoryStore(db_path)
    store.initialize()

    session_id = "session-1"
    history = [
        {"role": "user", "content": "hello"},
        {"role": "assistant", "content": "world"},
    ]

    store.save_conversation(session_id, history)

    summaries = store.list_conversations()
    assert summaries
    assert summaries[0].session_id == session_id

    loaded = store.load_conversation(session_id)
    assert loaded == history


def test_summary_title_uses_last_user_message_truncated_to_ten_words(tmp_path) -> None:
    db_path = tmp_path / "history.db"
    store = ChatHistoryStore(db_path)
    store.initialize()

    session_id = "session-2"
    history = [
        {"role": "user", "content": "first prompt"},
        {"role": "assistant", "content": "response"},
        {
            "role": "user",
            "content": "one two three four five six seven eight nine ten eleven twelve",
        },
    ]

    store.save_conversation(session_id, history)

    summaries = store.list_conversations()
    assert summaries
    assert summaries[0].title == "one two three four five six seven eight nine ten..."


def test_summary_title_updates_when_conversation_is_saved_again(tmp_path) -> None:
    db_path = tmp_path / "history.db"
    store = ChatHistoryStore(db_path)
    store.initialize()

    session_id = "session-3"
    first_history = [
        {"role": "user", "content": "initial question"},
        {"role": "assistant", "content": "initial answer"},
    ]
    store.save_conversation(session_id, first_history)

    second_history = [
        {"role": "user", "content": "initial question"},
        {"role": "assistant", "content": "initial answer"},
        {"role": "user", "content": "latest user message should be the title"},
        {"role": "assistant", "content": "latest answer"},
    ]
    store.save_conversation(session_id, second_history)

    summaries = store.list_conversations()
    assert summaries
    assert summaries[0].title == "latest user message should be the title"
