"""
Metrics capability contract.

Plugins that declare ``capabilities = ["metrics"]`` should implement
``get_metrics() -> MetricsResult`` so the metrics-aggregator plugin can
discover and collect them automatically via the capability system.
"""

from dataclasses import dataclass, field
from typing import Protocol, runtime_checkable


@dataclass
class MetricEntry:
    """A single metric data point.

    For histogram entries (``type="histogram"``), populate
    ``buckets``, ``histogram_sum``, and ``histogram_count`` so the
    aggregator can render proper Prometheus histogram exposition
    (``_bucket``, ``_sum``, ``_count`` lines).  ``value`` is ignored
    for histograms but kept for protocol compatibility.
    """

    name: str
    value: float
    type: str  # "gauge" | "counter" | "histogram"
    help: str = ""
    labels: dict[str, str] = field(default_factory=dict)
    # Histogram-specific fields (None for gauge/counter)
    buckets: list[tuple[float, int]] | None = None  # (le_bound, cumulative_count)
    histogram_sum: float | None = None
    histogram_count: int | None = None


@dataclass
class MetricsResult:
    """Structured collection of metrics returned by a provider."""

    gauges: list[MetricEntry] = field(default_factory=list)
    counters: list[MetricEntry] = field(default_factory=list)
    histograms: list[MetricEntry] = field(default_factory=list)

    @property
    def all_entries(self) -> list[MetricEntry]:
        """Flat list of all metric entries."""
        return self.gauges + self.counters + self.histograms


@runtime_checkable
class MetricsProvider(Protocol):
    """Protocol for plugins that expose metrics."""

    def get_metrics(self) -> MetricsResult: ...
