use std::env;
use std::fs;

#[derive(Debug)]
struct Entry {
    level: String,
    service: String,
    message: String,
}

fn parse_line(line: &str) -> Option<Entry> {
    let parts: Vec<&str> = line.splitn(3, '|').collect();
    if parts.len() != 3 {
        return None;
    }
    Some(Entry {
        level: parts[0].trim().to_string(),
        service: parts[1].trim().to_string(),
        message: parts[2].trim().to_string(),
    })
}

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.iter().any(|x| x == "--smoke-test") {
        println!("{{\"app\":\"log-audit-console-rust\",\"status\":\"source-ready\"}}");
        return;
    }

    let input = if args.len() > 1 {
        fs::read_to_string(&args[1]).unwrap_or_else(|_| SAMPLE.to_string())
    } else {
        SAMPLE.to_string()
    };

    let entries: Vec<Entry> = input.lines().filter_map(parse_line).collect();
    let error_count = entries.iter().filter(|x| x.level.eq_ignore_ascii_case("ERROR")).count();
    let warn_count = entries.iter().filter(|x| x.level.eq_ignore_ascii_case("WARN")).count();

    println!("Log Audit Console Rust");
    println!("Total entry  : {}", entries.len());
    println!("Error        : {}", error_count);
    println!("Warning      : {}", warn_count);

    for entry in entries.iter().take(5) {
        println!("- [{}] {} -> {}", entry.level, entry.service, entry.message);
    }
}

const SAMPLE: &str = r#"INFO|auth|login success
WARN|network|latency above threshold
ERROR|printer|device offline
INFO|asset|inventory sync complete"#;
