//! Prometheus metrics for Data Acquisition Service

use once_cell::sync::Lazy;
use prometheus::{
    register_counter, register_counter_vec, register_gauge, register_histogram_vec, Counter,
    CounterVec, Gauge, HistogramVec,
};

/// Service uptime in seconds
pub static SERVICE_UPTIME: Lazy<Gauge> = Lazy::new(|| {
    register_gauge!(
        "foxhunt_data_acquisition_uptime_seconds",
        "Service uptime in seconds"
    )
    .unwrap_or_else(|e| {
        eprintln!("FATAL: failed to register uptime gauge: {e}");
        std::process::abort()
    })
});

/// Active data feeds
pub static FEEDS_ACTIVE: Lazy<Gauge> = Lazy::new(|| {
    register_gauge!(
        "foxhunt_data_acquisition_feeds_active",
        "Number of active data feeds"
    )
    .unwrap_or_else(|e| {
        eprintln!("FATAL: failed to register feeds_active gauge: {e}");
        std::process::abort()
    })
});

/// Total records received
pub static RECORDS_RECEIVED: Lazy<CounterVec> = Lazy::new(|| {
    register_counter_vec!(
        "foxhunt_data_acquisition_records_received_total",
        "Total records received from data feeds",
        &["symbol", "feed_type"]
    )
    .unwrap_or_else(|e| {
        eprintln!("FATAL: failed to register records_received counter: {e}");
        std::process::abort()
    })
});

/// Total errors
pub static ERRORS: Lazy<Counter> = Lazy::new(|| {
    register_counter!(
        "foxhunt_data_acquisition_errors_total",
        "Total data acquisition errors"
    )
    .unwrap_or_else(|e| {
        eprintln!("FATAL: failed to register errors counter: {e}");
        std::process::abort()
    })
});

/// Feed processing latency
pub static FEED_LATENCY: Lazy<HistogramVec> = Lazy::new(|| {
    register_histogram_vec!(
        "foxhunt_data_acquisition_feed_latency_seconds",
        "Feed processing latency in seconds",
        &["feed_type"],
        vec![0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0, 5.0]
    )
    .unwrap_or_else(|e| {
        eprintln!("FATAL: failed to register feed_latency histogram: {e}");
        std::process::abort()
    })
});

/// Initialize all metrics (force lazy registration)
pub fn init_metrics() {
    let _ = &*SERVICE_UPTIME;
    let _ = &*FEEDS_ACTIVE;
    let _ = &*RECORDS_RECEIVED;
    let _ = &*ERRORS;
    let _ = &*FEED_LATENCY;
}

/// Update service uptime metric
pub fn update_uptime(start_time: std::time::Instant) {
    SERVICE_UPTIME.set(start_time.elapsed().as_secs_f64());
}
