"""observability.metrics — Prometheus-style metrics (in-memory counters for MVP)."""
from __future__ import annotations
import time
from collections import defaultdict
from typing import Dict


class Metrics:
    def __init__(self):
        self._counters: Dict[str, int] = defaultdict(int)
        self._histograms: Dict[str, list] = defaultdict(list)

    def inc(self, name: str, labels: Dict = None, value: int = 1):
        key = f"{name}" + (f"{{{','.join(f'{k}={v}' for k,v in labels.items())}}}" if labels else "")
        self._counters[key] += value

    def observe(self, name: str, value: float, labels: Dict = None):
        key = f"{name}" + (f"{{{','.join(f'{k}={v}' for k,v in labels.items())}}}" if labels else "")
        self._histograms[key].append(value)

    def record_request(self, agent_id: str, status: str, duration_ms: float, tokens: int = 0):
        self.inc("agentpaas_requests_total", {"agent_id": agent_id, "status": status})
        self.observe("agentpaas_request_duration_ms", duration_ms, {"agent_id": agent_id})
        if tokens:
            self.inc("agentpaas_tokens_total", {"agent_id": agent_id}, tokens)

    def snapshot(self) -> Dict:
        return {"counters": dict(self._counters),
                "histograms": {k: {"count": len(v), "mean": sum(v)/len(v) if v else 0, "max": max(v) if v else 0}
                               for k, v in self._histograms.items()}}


metrics = Metrics()
