"""Observability gRPC mixin for logs and metrics."""

from __future__ import annotations

from typing import Protocol

from noteflow.infrastructure.logging import get_log_buffer
from noteflow.infrastructure.metrics import get_metrics_collector
from noteflow.infrastructure.persistence.constants import DEFAULT_LOG_LIMIT, MAX_LOG_LIMIT

from ..proto import noteflow_pb2
from ._types import GrpcContext
from .converters import metrics_to_proto


class ObservabilityServicer(Protocol):
    """Protocol for observability mixin hosts (no required attributes)."""

class ObservabilityMixin:
    """Mixin providing observability endpoints for logs and metrics.

    Exposes recent application logs and system performance metrics
    for the analytics dashboard.
    """

    async def GetRecentLogs(
        self: ObservabilityServicer,
        request: noteflow_pb2.GetRecentLogsRequest,
        context: GrpcContext,
    ) -> noteflow_pb2.GetRecentLogsResponse:
        """Get recent application logs.

        Returns log entries from the in-memory buffer, optionally filtered
        by log level or source component.
        """
        buffer = get_log_buffer()

        # Apply defaults and limits
        limit = min(request.limit or DEFAULT_LOG_LIMIT, MAX_LOG_LIMIT)
        level = request.level or None
        source = request.source or None

        entries = buffer.get_recent(
            limit=limit,
            level=level,
            source=source,
        )

        return noteflow_pb2.GetRecentLogsResponse(
            logs=[
                noteflow_pb2.LogEntryProto(
                    timestamp=entry.timestamp.isoformat(),
                    level=entry.level,
                    source=entry.source,
                    message=entry.message,
                    details=entry.details,
                )
                for entry in entries
            ],
        )

    async def GetPerformanceMetrics(
        self: ObservabilityServicer,
        request: noteflow_pb2.GetPerformanceMetricsRequest,
        context: GrpcContext,
    ) -> noteflow_pb2.GetPerformanceMetricsResponse:
        """Get system performance metrics.

        Returns current metrics plus historical data points for
        time-series visualization.
        """
        collector = get_metrics_collector()

        # Collect current metrics
        current = collector.collect_now()

        # Get history
        history_limit = request.history_limit or 60
        history = collector.get_history(limit=history_limit)

        return noteflow_pb2.GetPerformanceMetricsResponse(
            current=metrics_to_proto(current),
            history=[metrics_to_proto(m) for m in history],
        )
