use serde::Deserialize;
use std::fs;
use std::path::Path;

#[derive(Deserialize)]
pub struct Config {
    pub sender: Vec<SenderConfig>,
}

#[derive(Deserialize, Clone)]
pub struct SenderConfig {
    /// Destination IP address or hostname.
    pub address: String,

    /// Destination port (default: 5005).
    #[serde(default = "default_port")]
    pub port: u16,

    /// Source network interface (e.g. "eth0"). Auto-discovered if omitted.
    pub interface: Option<String>,

    /// Number of packer/sender thread pairs (default: 5).
    #[serde(default = "default_threads")]
    pub threads: usize,
}

fn default_port() -> u16 {
    5005
}

fn default_threads() -> usize {
    5
}

impl Config {
    pub fn load(path: &Path) -> Result<Self, String> {
        let content = fs::read_to_string(path)
            .map_err(|e| format!("Failed to read config file '{}': {}", path.display(), e))?;
        let config: Config = toml::from_str(&content)
            .map_err(|e| format!("Failed to parse config file '{}': {}", path.display(), e))?;

        if config.sender.is_empty() {
            return Err("Config must define at least one [[sender]]".into());
        }

        for (i, s) in config.sender.iter().enumerate() {
            if s.threads == 0 {
                return Err(format!("sender[{}]: threads must be >= 1", i));
            }
        }

        Ok(config)
    }
}
