"""Tests for Reasoning Audit Trail feature."""

import pytest

from locidb.core.db import LociDB


@pytest.fixture
def db(tmp_path):
    loci = LociDB(path=tmp_path / "test.loci")
    yield loci
    loci.close()


class TestStoreTrace:
    def test_store_trace_returns_id(self, db):
        trace_id = db.store_trace(
            query="How to optimize?",
            node_ids_used=["abc123"],
            response="Use caching",
        )
        assert isinstance(trace_id, str)
        assert len(trace_id) == 32  # UUID hex

    def test_store_trace_with_metadata(self, db):
        trace_id = db.store_trace(
            query="Test query",
            node_ids_used=[],
            metadata={"model": "gpt-4o", "tokens": 150},
        )
        traces = db.traces()
        assert len(traces) == 1
        assert traces[0]["metadata"]["model"] == "gpt-4o"


class TestListTraces:
    def test_list_traces_empty(self, db):
        assert db.traces() == []

    def test_list_traces_returns_recent(self, db):
        db.store_trace(query="Q1", node_ids_used=["a"])
        db.store_trace(query="Q2", node_ids_used=["b"])
        traces = db.traces()
        assert len(traces) == 2

    def test_list_traces_filter_by_scope(self, db):
        db.store_trace(query="Q1", node_ids_used=[], scope="project:alpha")
        db.store_trace(query="Q2", node_ids_used=[], scope="project:beta")
        traces = db.traces(scope="project:alpha")
        assert len(traces) == 1
        assert traces[0]["query"] == "Q1"


class TestExplain:
    def test_explain_returns_text(self, db):
        node = db.memorize("Delivery uses hub model", entities=["delivery"])
        trace_id = db.store_trace(
            query="How does delivery work?",
            node_ids_used=[node.id],
            response="It uses a hub-spoke model.",
        )
        explanation = db.explain(trace_id)
        assert "How does delivery work?" in explanation
        assert "hub" in explanation.lower()

    def test_explain_nonexistent_trace(self, db):
        assert db.explain("nonexistent_id") is None


class TestTracesUsingNode:
    def test_find_traces_by_node(self, db):
        node = db.memorize("Important decision", entities=["decision"])
        db.store_trace(query="Q1", node_ids_used=[node.id])
        db.store_trace(query="Q2", node_ids_used=["other_node"])
        db.store_trace(query="Q3", node_ids_used=[node.id, "other_node"])
        traces = db.traces_using_node(node.id)
        assert len(traces) == 2

    def test_no_traces_for_unused_node(self, db):
        assert db.traces_using_node("unused") == []


class TestTracePersistence:
    def test_survives_reopen(self, tmp_path):
        db1 = LociDB(path=tmp_path / "trace.loci")
        tid = db1.store_trace(query="Persist test", node_ids_used=["x"])
        db1.close()

        db2 = LociDB(path=tmp_path / "trace.loci")
        traces = db2.traces()
        assert len(traces) == 1
        assert traces[0]["id"] == tid
        db2.close()
