use std::net::IpAddr;
use std::path::PathBuf;

use anyhow::{bail, Context};
use blax_webrtc_sfu::server::{self, Config};

const USAGE: &str = "blax-webrtc-sfu — Rust SFU data plane for blax-software/laravel-webrtc

USAGE:
    blax-webrtc-sfu [OPTIONS]

OPTIONS:
    --socket <path>      Control socket path   [default: /tmp/blax-webrtc-sfu.sock]
    --udp-ip <ip>        Media UDP bind ip     [default: 0.0.0.0]
    --udp-port <port>    Media UDP port        [default: 0 = ephemeral]
    --public-ip <ip>     IP advertised to browsers in ICE candidates
                         [default: the default-route interface address]
    -h, --help           Show this help
";

fn main() -> anyhow::Result<()> {
    env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();

    let mut config = Config {
        socket: PathBuf::from("/tmp/blax-webrtc-sfu.sock"),
        udp_ip: IpAddr::from([0, 0, 0, 0]),
        udp_port: 0,
        public_ip: None,
    };

    let mut args = std::env::args().skip(1);
    while let Some(flag) = args.next() {
        let mut value = |name: &str| {
            args.next()
                .with_context(|| format!("{name} requires a value"))
        };
        match flag.as_str() {
            "--socket" => config.socket = PathBuf::from(value("--socket")?),
            "--udp-ip" => config.udp_ip = value("--udp-ip")?.parse().context("--udp-ip")?,
            "--udp-port" => {
                config.udp_port = value("--udp-port")?.parse().context("--udp-port")?
            }
            "--public-ip" => {
                config.public_ip = Some(value("--public-ip")?.parse().context("--public-ip")?)
            }
            "-h" | "--help" => {
                print!("{USAGE}");
                return Ok(());
            }
            other => bail!("unknown option: {other}\n\n{USAGE}"),
        }
    }

    server::run(config)
}
