"""Tests for session tracking."""
import pytest
from greymatter_core.db import SQLiteDatabase
from greymatter_core.sessions import SessionManager


@pytest.fixture
def db():
    return SQLiteDatabase(":memory:")


@pytest.fixture
def sessions(db):
    return SessionManager(db)


def test_start_session(sessions):
    s = sessions.start()
    assert s["id"] is not None
    assert s["started_at"] is not None
    assert s["ended_at"] is None


def test_end_session(sessions):
    s = sessions.start()
    ended = sessions.end(s["id"], summary="Completed task A")
    assert ended["ended_at"] is not None
    assert ended["summary"] == "Completed task A"


def test_get_current(sessions):
    assert sessions.get_current() is None
    s = sessions.start()
    current = sessions.get_current()
    assert current["id"] == s["id"]
    sessions.end(s["id"])
    assert sessions.get_current() is None


def test_get_recent(sessions):
    sessions.start()
    sessions.start()
    recent = sessions.get_recent(limit=5)
    assert len(recent) == 2


def test_session_has_state_columns(sessions):
    s = sessions.start()
    assert s.get("state") == "active" or s.get("state") is None
    assert s.get("compaction_count") is not None or "compaction_count" not in s


def test_checkpoint_creates_record(sessions):
    s = sessions.start()
    cp = sessions.checkpoint(s["id"], context_summary="Testing checkpoint", open_items="[]")
    assert "checkpoint_id" in cp
    assert cp["session_id"] == s["id"]
    assert "checkpoint_at" in cp


def test_get_latest_checkpoint(sessions):
    s = sessions.start()
    sessions.checkpoint(s["id"], context_summary="First")
    sessions.checkpoint(s["id"], context_summary="Second")
    latest = sessions.get_latest_checkpoint(s["id"])
    assert latest is not None
    assert latest["context_summary"] == "Second"


def test_update_state(sessions):
    s = sessions.start()
    result = sessions.update_state(s["id"], "compacting", active_work_item_id="wi-123")
    assert result is True
    updated = sessions.get(s["id"])
    assert updated["state"] == "compacting"
    assert updated["active_work_item_id"] == "wi-123"


def test_increment_compaction(sessions):
    s = sessions.start()
    count1 = sessions.increment_compaction(s["id"])
    assert count1 == 1
    count2 = sessions.increment_compaction(s["id"])
    assert count2 == 2


def test_checkpoint_nonexistent_session(sessions):
    result = sessions.checkpoint("nonexistent-id")
    assert "error" in result
