#!/usr/bin/env python3
"""
Observability endpoints for FlowTorch production.
- Enhanced /health
- /metrics (Prometheus-compatible)
- /receipts (recent signed proofs)
- /cds (Control Diagnostics Status)
"""

import time
import json
from pathlib import Path
from typing import Dict, Any, List
from collections import deque
from datetime import datetime, timezone


class MetricsCollector:
    """
    Prometheus-compatible metrics collector.
    Tracks requests, errors, basin locks, MI, latency, energy.
    """

    def __init__(self):
        self.start_time = time.time()

        # Counters
        self.requests_total = 0
        self.errors_total = 0
        self.basin_locks_total = 0

        # Sums (for rates/averages)
        self.mi_sum = 0.0
        self.latency_sum = 0.0
        self.energy_sum = 0.0

        # Recent receipts (last 100)
        self.recent_receipts = deque(maxlen=100)

        # Per-cardinality stats
        self.cardinality_counts = {2: 0, 3: 0, 4: 0, 8: 0}

    def record_request(self):
        """Record incoming request."""
        self.requests_total += 1

    def record_error(self):
        """Record error."""
        self.errors_total += 1

    def record_basin_lock(
        self,
        mi: float,
        latency: float,
        energy: float,
        cardinality: int,
        receipt: Dict[str, Any]
    ):
        """
        Record successful basin lock.

        Args:
            mi: Mutual information (bits)
            latency: Request latency (seconds)
            energy: Energy consumption (μJ)
            cardinality: Basin count
            receipt: Signed receipt
        """
        self.basin_locks_total += 1
        self.mi_sum += mi
        self.latency_sum += latency
        self.energy_sum += energy

        if cardinality in self.cardinality_counts:
            self.cardinality_counts[cardinality] += 1

        # Store receipt
        self.recent_receipts.append({
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "receipt": receipt,
        })

    def get_metrics(self) -> Dict[str, Any]:
        """Get Prometheus-compatible metrics."""
        uptime = time.time() - self.start_time

        return {
            # Counters
            "flowtorch_requests_total": self.requests_total,
            "flowtorch_errors_total": self.errors_total,
            "flowtorch_basin_locks_total": self.basin_locks_total,

            # Sums (for Prometheus rate/avg calculations)
            "flowtorch_mi_bits_sum": self.mi_sum,
            "flowtorch_latency_seconds_sum": self.latency_sum,
            "flowtorch_energy_uJ_sum": self.energy_sum,

            # Per-cardinality
            "flowtorch_binary_locks_total": self.cardinality_counts[2],
            "flowtorch_trit_locks_total": self.cardinality_counts[3],
            "flowtorch_quad_locks_total": self.cardinality_counts[4],
            "flowtorch_octal_locks_total": self.cardinality_counts[8],

            # Uptime
            "flowtorch_uptime_seconds": uptime,

            # Timestamp
            "timestamp": datetime.now(timezone.utc).isoformat(),
        }

    def get_receipts(self, limit: int = 10) -> List[Dict[str, Any]]:
        """Get recent receipts (most recent first)."""
        receipts = list(self.recent_receipts)
        receipts.reverse()  # Most recent first
        return receipts[:limit]


# Global metrics collector
_metrics = MetricsCollector()


def get_metrics() -> MetricsCollector:
    """Get global metrics collector."""
    return _metrics


def health_check() -> Dict[str, Any]:
    """
    Enhanced health check.
    Returns detailed status including engine, CDC, GA-OFF, and uptime.
    """
    import os

    metrics = get_metrics()
    uptime = time.time() - metrics.start_time

    # Check engine availability
    engine_available = False
    engine_error = None
    try:
        import importlib
        engine = importlib.import_module("artifacts.context_pack.flowtorch.flowtorch_engine")
        if hasattr(engine, "run_prefill_decode") or hasattr(engine, "generate"):
            engine_available = True
    except Exception as e:
        engine_error = str(e)

    # Check CDC availability
    cdc_available = False
    cdc_error = None
    try:
        from helix_cdc.cdc_decode import CDCDecoder
        cdc_available = True
    except Exception as e:
        cdc_error = str(e)

    # Check GA-OFF mode
    ga_nudge_forbid = os.getenv("GA_NUDGE_FORBID", "0") == "1"

    # Overall health
    ok = engine_available and ga_nudge_forbid

    return {
        "ok": ok,
        "engine_available": engine_available,
        "engine_error": engine_error,
        "cdc_available": cdc_available,
        "cdc_error": cdc_error,
        "ga_nudge_forbid": ga_nudge_forbid,
        "uptime_seconds": uptime,
        "request_count": metrics.requests_total,
        "error_count": metrics.errors_total,
        "basin_locks_count": metrics.basin_locks_total,
        "timestamp": datetime.now(timezone.utc).isoformat(),
    }


def cds_status() -> Dict[str, Any]:
    """
    Control Diagnostics Status - real-time steering health.
    Returns safety monitor status.
    """
    from edge_app.safety import get_monitor

    monitor = get_monitor()
    status = monitor.get_status()

    return status
