"""Annotation dataclass and request ID tracking via ContextVar."""

import uuid
from contextvars import ContextVar
from dataclasses import dataclass, field
from datetime import UTC, datetime

_last_request_id: ContextVar[str | None] = ContextVar("_last_request_id", default=None)


def generate_request_id() -> str:
    return str(uuid.uuid4())


def set_last_request_id(request_id: str) -> None:
    _last_request_id.set(request_id)


def get_last_request_id() -> str | None:
    return _last_request_id.get()


@dataclass(slots=True)
class Annotation:
    request_id: str
    timestamp: str = field(default_factory=lambda: datetime.now(UTC).isoformat())
    metadata: dict[str, str] = field(default_factory=dict)

    def to_dict(self) -> dict:
        return {
            "request_id": self.request_id,
            "timestamp": self.timestamp,
            "metadata": self.metadata,
        }
