use falcorn_sdk::LoggingClient;
use falcorn_sdk::proto::logging::{
    DEFAULT_LOG_SOCKET, PLUGIN_FILTER_ACCESS_LOG, PLUGIN_FILTER_ALL, PLUGIN_FILTER_LOG_MESSAGE,
    PLUGIN_FILTER_METRICS,
};
use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let socket = env::var("FALCORN_LOG_SOCKET").unwrap_or_else(|_| DEFAULT_LOG_SOCKET.to_string());
    let token = env::var("FALCORN_LOG_TOKEN").ok();
    let client_name = env::var("FALCORN_LOG_CLIENT").ok();
    let filter = env::var("FALCORN_LOG_FILTER")
        .ok()
        .and_then(|value| value.parse::<u8>().ok())
        .unwrap_or(PLUGIN_FILTER_ALL);

    let mut builder = LoggingClient::builder(socket);
    if let Some(token) = token {
        builder = builder.auth_token(token);
    }
    if let Some(client_name) = client_name {
        builder = builder.client_name(client_name);
    }
    builder = builder.filter_mask(filter);

    let mut client = builder.connect()?;
    println!(
        "Connected. Filters: log={} access={} metrics={} (mask={:#04x})",
        filter & PLUGIN_FILTER_LOG_MESSAGE != 0,
        filter & PLUGIN_FILTER_ACCESS_LOG != 0,
        filter & PLUGIN_FILTER_METRICS != 0,
        filter
    );

    loop {
        let event = client.next_event()?;
        match event {
            falcorn_sdk::proto::logging::PluginEvent::LogMessage {
                ts_millis,
                level,
                pid,
                worker_id,
                message,
            } => {
                println!(
                    "[{}] {} pid={} worker={:?} - {}",
                    ts_millis,
                    level.as_str(),
                    pid,
                    worker_id,
                    message
                );
            }
            falcorn_sdk::proto::logging::PluginEvent::AccessLog {
                ts_millis,
                remote,
                method,
                uri,
                status,
                duration_micros,
                ..
            } => {
                println!(
                    "[{}] {} {} {} status={} {}us",
                    ts_millis, remote, method, uri, status, duration_micros
                );
            }
            falcorn_sdk::proto::logging::PluginEvent::Metrics(metrics) => {
                println!(
                    "METRICS rps={:.2} success_rate={:.4} avg_us={} active_conn={}",
                    metrics.requests_per_second,
                    metrics.success_rate,
                    metrics.avg_response_time_micros,
                    metrics.active_connections
                );
            }
        }
    }
}
