"""Full trace logging — captures every LLM call, tool use, and reasoning step."""

from __future__ import annotations

from agent_scout.db.database import Database
from agent_scout.db.models import TraceEntry
from agent_scout.events import Event, EventBus


class Tracer:
    """Subscribes to the event bus and persists all events as trace entries in SQLite.

    Provides an OTEL-compatible span structure via parent_id chaining.
    """

    def __init__(self, event_bus: EventBus, db: Database) -> None:
        self._bus = event_bus
        self._db = db
        self._unsub = self._bus.subscribe(self._handle_event, event_type=None)
        self._enabled = True

    async def _handle_event(self, event: Event) -> None:
        if not self._enabled:
            return
        trace = TraceEntry(
            id=event.event_id,
            task_id=event.task_id,
            event_type=event.event_type.value,
            data=event.data,
            parent_id=event.parent_event_id,
            timestamp=event.timestamp,
        )
        await self._db.store_trace(trace)

    async def get_task_traces(
        self,
        task_id: str,
        event_type: str | None = None,
        limit: int = 100,
    ) -> list[TraceEntry]:
        return await self._db.get_traces(task_id=task_id, event_type=event_type, limit=limit)

    async def get_all_traces(
        self,
        event_type: str | None = None,
        limit: int = 100,
    ) -> list[TraceEntry]:
        return await self._db.get_traces(event_type=event_type, limit=limit)

    def disable(self) -> None:
        self._enabled = False

    def enable(self) -> None:
        self._enabled = True

    def stop(self) -> None:
        """Unsubscribe from the event bus."""
        self._unsub()
