"""Trace context for capturing well operations."""

from __future__ import annotations

from contextvars import ContextVar
from dataclasses import dataclass, field

from biocompute.exceptions import BiocomputeError
from biocompute.ops import Op

_current_trace: ContextVar[Trace | None] = ContextVar("biocompute_trace", default=None)


def get_current_trace() -> Trace:
    """Get the active trace context.

    Raises:
        BiocomputeError: If no Competition is active.
    """
    t = _current_trace.get()
    if t is None:
        raise BiocomputeError("wells() called without an active Competition instance")
    return t


@dataclass
class Trace:
    """Collects operations during experiment definition."""

    ops: list[Op] = field(default_factory=list)
    well_count: int = 0

    def emit(self, op: Op) -> None:
        """Record an operation."""
        self.ops.append(op)

    def update_well_count(self, idx: int) -> None:
        """Update the total well count based on accessed index."""
        self.well_count = max(self.well_count, idx + 1)
