"""Prometheus metrics for the MCP server. Scraped via /metrics on the WSGI side."""

import time

from prometheus_client import Counter, Histogram

mcp_tool_invocations_total = Counter(
    "mcp_tool_invocations_total",
    "Total MCP tool invocations.",
    ["tool", "status"],
)

mcp_tool_duration_seconds = Histogram(
    "mcp_tool_duration_seconds",
    "MCP tool execution duration in seconds.",
    ["tool"],
    buckets=(0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0),
)

mcp_auth_failures_total = Counter(
    "mcp_auth_failures_total",
    "Total MCP authentication failures.",
    ["reason"],
)


class record_tool_call:
    """Context manager that records invocation count + duration for a tool."""

    def __init__(self, tool_name: str):
        self.tool_name = tool_name
        self.started_at = 0.0

    def __enter__(self):
        self.started_at = time.monotonic()
        return self

    def __exit__(self, exc_type, exc, tb):
        duration = time.monotonic() - self.started_at
        status = "error" if exc_type else "success"
        mcp_tool_invocations_total.labels(tool=self.tool_name, status=status).inc()
        mcp_tool_duration_seconds.labels(tool=self.tool_name).observe(duration)
        return False  # never suppress exceptions
