"""
CoreMetricsProvider — exposes framework-level metrics from FastPluggy core.

Registered in GlobalRegistry under "core_metrics_provider" so the metrics
plugin can discover it and include core metrics in /api/metrics.

Note: the metrics router auto-prefixes names with ``fp_core_``, so metric
names here should NOT start with ``fp_``.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from .metrics import MetricEntry, MetricsResult

if TYPE_CHECKING:
    from fastpluggy.fastpluggy import FastPluggy


class CoreMetricsProvider:
    """Implements MetricsProvider protocol for FastPluggy core."""

    def __init__(self, fast_pluggy: FastPluggy) -> None:
        self._fp = fast_pluggy

    def get_metrics(self) -> MetricsResult:
        mm = self._fp.module_manager
        events = self._fp.events

        # Plugin counts
        loaded = sum(1 for ps in mm.modules.values() if ps.loaded)
        enabled = sum(1 for ps in mm.modules.values() if ps.enabled)
        failed = sum(1 for ps in mm.modules.values() if ps.enabled and not ps.loaded)

        gauges = [
            MetricEntry(name="plugins_loaded", value=loaded, type="gauge",
                        help="Total loaded plugin count"),
            MetricEntry(name="plugins_enabled", value=enabled, type="gauge",
                        help="Enabled plugin count"),
            MetricEntry(name="plugins_failed", value=failed, type="gauge",
                        help="Failed plugin count"),
            MetricEntry(name="load_time_ms", value=getattr(self._fp, '_load_time_ms', 0),
                        type="gauge", help="Total load_app() duration in ms"),
            MetricEntry(name="event_listeners_count", value=events.listener_count(),
                        type="gauge", help="Current event listener count"),
        ]

        # Per-plugin load times
        for name, duration in getattr(mm, '_plugin_load_times', {}).items():
            gauges.append(MetricEntry(
                name="plugin_load_time_ms", value=duration, type="gauge",
                help="Per-plugin load time in ms",
                labels={"plugin": name},
            ))

        counters = [
            MetricEntry(name="events_dispatched_total",
                        value=getattr(events, 'events_dispatched', 0),
                        type="counter", help="Total events emitted"),
        ]

        return MetricsResult(gauges=gauges, counters=counters)
