"""Trace context manager — groups related decisions into one audit trail."""

import uuid
from typing import Optional


class TraceContext:
    """
    Groups related log entries under one trace ID.

    Usage:
        with sealvera.trace("pipeline-001", "Document Pipeline") as t:
            result = agent.run(task)
            t.log(action="agent_run", decision="COMPLETED", output={"result": result})

        # Or without context manager:
        t = sealvera.trace("pipeline-001")
        t.log(action="step_1", decision="COMPLETED", ...)
        t.log(action="step_2", decision="COMPLETED", ...)
    """

    def __init__(self, client, trace_id: str = None, trace_name: str = None):
        self._client     = client
        self._trace_id   = trace_id or str(uuid.uuid4())
        self._trace_name = trace_name
        self._entries    = []

    @property
    def trace_id(self) -> str:
        return self._trace_id

    def log(
        self,
        action: str,
        decision: str,
        input: dict = None,
        output: dict = None,
        reasoning: list = None,
        agent: str = None,
        model: str = None,
        blocking: bool = False,
    ) -> dict:
        """Log a decision within this trace."""
        result = self._client.log(
            action=action,
            decision=decision,
            input=input or {},
            output=output or {},
            reasoning=reasoning or [],
            agent=agent,
            trace_id=self._trace_id,
            trace_name=self._trace_name,
            model=model,
            blocking=blocking,
        )
        self._entries.append(result)
        return result

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        # Don't suppress exceptions
        return False

    def __repr__(self):
        return f"<TraceContext trace_id={self._trace_id!r} entries={len(self._entries)}>"
