use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
struct FleetEvent {
    source: String,
    event_type: String,
    payload: serde_json::Value,
    timestamp: u64,
}

#[derive(Debug)]
struct RouteRule {
    pattern: String,
    target: String,
    priority: u8,
}

struct EventRouter {
    rules: Vec<RouteRule>,
    stats: HashMap<String, u64>,
}

impl EventRouter {
    fn new() -> Self {
        Self {
            rules: Vec::new(),
            stats: HashMap::new(),
        }
    }

    fn add_rule(&mut self, pattern: String, target: String, priority: u8) {
        self.rules.push(RouteRule { pattern, target, priority });
        self.rules.sort_by(|a, b| b.priority.cmp(&a.priority));
    }

    fn route(&mut self, event: &FleetEvent) -> Option<String> {
        for rule in &self.rules {
            if event.event_type.contains(&rule.pattern) {
                *self.stats.entry(rule.target.clone()).or_insert(0) += 1;
                return Some(rule.target.clone());
            }
        }
        None
    }

    fn stats(&self) -> &HashMap<String, u64> {
        &self.stats
    }
}

fn main() {
    let mut router = EventRouter::new();
    router.add_rule("telemetry".into(), "metrics-sink".into(), 10);
    router.add_rule("alert".into(), "notification-hub".into(), 20);
    router.add_rule("deploy".into(), "ci-pipeline".into(), 15);

    let events = vec![
        FleetEvent {
            source: "node-1".into(),
            event_type: "telemetry.cpu".into(),
            payload: serde_json::json!({"usage": 72.5}),
            timestamp: 1718000000,
        },
        FleetEvent {
            source: "node-3".into(),
            event_type: "alert.disk_full".into(),
            payload: serde_json::json!({"path": "/var", "pct": 98}),
            timestamp: 1718000010,
        },
        FleetEvent {
            source: "ci".into(),
            event_type: "deploy.started".into(),
            payload: serde_json::json!({"service": "api-gateway"}),
            timestamp: 1718000020,
        },
    ];

    for event in &events {
        match router.route(event) {
            Some(target) => println!("[ROUTED] {} → {}", event.event_type, target),
            None => println!("[DROPPED] {}", event.event_type),
        }
    }

    println!("\nRouting stats: {:?}", router.stats());
}
