"""Tests for swarm.event_log — WAL mode, basic operations, and EventBus bridge."""

import pytest

from swarm.event_log import EventType, _ensure_db, log_event


@pytest.fixture(autouse=True)
def tmp_event_db(tmp_path, monkeypatch):
    """Redirect event_log writes to a temp directory."""
    db_path = tmp_path / "events.db"
    monkeypatch.setattr("swarm.event_log.DB_PATH", db_path)
    yield db_path


class TestEventLogWAL:
    """Verify WAL mode is enabled for the event log database."""

    def test_event_db_uses_wal(self):
        conn = _ensure_db()
        try:
            mode = conn.execute("PRAGMA journal_mode").fetchone()[0]
            assert mode == "wal", f"Expected WAL mode, got {mode}"
        finally:
            conn.close()

    def test_event_db_busy_timeout(self):
        conn = _ensure_db()
        try:
            timeout = conn.execute("PRAGMA busy_timeout").fetchone()[0]
            assert timeout == 5000
        finally:
            conn.close()


class TestEventLogBasics:
    """Basic event logging operations."""

    def test_log_event_returns_entry(self):
        entry = log_event(EventType.SYSTEM_INFO, source="test", data={"msg": "hello"})
        assert entry.id
        assert entry.event_type == EventType.SYSTEM_INFO
        assert entry.source == "test"

    def test_log_event_persists(self):
        log_event(EventType.TASK_CREATED, source="test", task_id="t1")
        from swarm.event_log import get_task_events

        events = get_task_events("t1")
        assert len(events) == 1
        assert events[0].event_type == EventType.TASK_CREATED

    def test_log_event_with_agent_id(self):
        entry = log_event(
            EventType.AGENT_JOINED,
            source="test",
            agent_id="forge",
            data={"persona_id": "forge"},
        )
        assert entry.agent_id == "forge"

    def test_log_event_data_roundtrip(self):
        data = {"bid_sats": 42, "reason": "testing"}
        entry = log_event(EventType.BID_SUBMITTED, source="test", data=data)
        assert entry.data["bid_sats"] == 42
        assert entry.data["reason"] == "testing"
