"""Metric definitions — no-op when OTel not installed"""

try:
    from opentelemetry import metrics

    _OTEL_AVAILABLE = True
except ImportError:
    _OTEL_AVAILABLE = False


class _NoOpCounter:
    """No-op counter used when OTel is not installed."""

    def add(self, *args, **kwargs):
        pass


class _NoOpHistogram:
    """No-op histogram used when OTel is not installed."""

    def record(self, *args, **kwargs):
        pass


class _NoOpUpDownCounter:
    """No-op up-down counter used when OTel is not installed."""

    def add(self, *args, **kwargs):
        pass


def get_meter(name: str = "fischer.agentkit"):
    """Get meter — returns None if OTel not installed."""
    if _OTEL_AVAILABLE:
        return metrics.get_meter(name)
    return None


# Lazy-initialized metric instruments
_agent_request_counter = None
_agent_duration_histogram = None
_llm_token_histogram = None
_tool_duration_histogram = None
_pipeline_step_histogram = None


def _get_counter(name: str, description: str, unit: str = "1"):
    meter = get_meter()
    if meter is None:
        return _NoOpCounter()
    return meter.create_counter(name=name, description=description, unit=unit)


def _get_histogram(name: str, description: str, unit: str = "ms"):
    meter = get_meter()
    if meter is None:
        return _NoOpHistogram()
    return meter.create_histogram(name=name, description=description, unit=unit)


def agent_request_counter():
    """Total agent execution requests."""
    global _agent_request_counter
    if _agent_request_counter is None:
        _agent_request_counter = _get_counter(
            "agent.request.total", "Total agent execution requests"
        )
    return _agent_request_counter


def agent_duration_histogram():
    """Agent execution duration."""
    global _agent_duration_histogram
    if _agent_duration_histogram is None:
        _agent_duration_histogram = _get_histogram(
            "agent.execution.duration", "Agent execution duration"
        )
    return _agent_duration_histogram


def llm_token_histogram():
    """Token usage per LLM call."""
    global _llm_token_histogram
    if _llm_token_histogram is None:
        _llm_token_histogram = _get_histogram(
            "gen_ai.usage.tokens", "Token usage per LLM call", unit="1"
        )
    return _llm_token_histogram


def tool_duration_histogram():
    """Tool call duration."""
    global _tool_duration_histogram
    if _tool_duration_histogram is None:
        _tool_duration_histogram = _get_histogram(
            "tool.call.duration", "Tool call duration"
        )
    return _tool_duration_histogram


def pipeline_step_histogram():
    """Pipeline step duration."""
    global _pipeline_step_histogram
    if _pipeline_step_histogram is None:
        _pipeline_step_histogram = _get_histogram(
            "pipeline.step.duration", "Pipeline step duration"
        )
    return _pipeline_step_histogram
