"""Observability helpers for {{ project_name }}."""

from __future__ import annotations

import logging
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Any


@dataclass
class StatusUpdate:
    """Status update payload for UI hooks."""

    status: str
    message: str
    timestamp: datetime = field(default_factory=lambda: datetime.now(UTC))


class AgentTelemetry:
    """Simple telemetry middleware for flow events."""

    def __init__(
        self,
        *,
        flow_name: str,
        logger: logging.Logger,
        status_callback: Callable[[StatusUpdate], None] | None = None,
    ) -> None:
        self.flow_name = flow_name
        self.logger = logger
        self._status_callback = status_callback
        self.events: list[dict[str, Any]] = []

    def record_flow_event(self, event_type: str, payload: dict[str, Any]) -> None:
        """Record a flow event."""
        event = {"flow": self.flow_name, "type": event_type, **payload}
        self.events.append(event)

        if event_type == "error":
            self.logger.error(f"flow_{event_type}", extra=event)
        elif event_type == "finish":
            self.logger.info(f"flow_{event_type}", extra=event)
        else:
            self.logger.debug(f"flow_{event_type}", extra=event)

    def publish_status(self, update: StatusUpdate) -> None:
        """Forward status updates to callback or logs."""
        if self._status_callback:
            self._status_callback(update)
        else:
            self.logger.info(
                "status_update",
                extra={
                    "flow": self.flow_name,
                    "status": update.status,
                    "message": update.message,
                    "timestamp": update.timestamp.isoformat(),
                },
            )
