use falcorn_sdk::ControlClient;
use falcorn_sdk::proto::control::DEFAULT_CONTROL_SOCKET;
use std::env;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut args = env::args().skip(1);
    let action = args.next().unwrap_or_else(|| "status".to_string());

    let socket =
        env::var("FALCORN_CONTROL_SOCKET").unwrap_or_else(|_| DEFAULT_CONTROL_SOCKET.to_string());
    let token = env::var("FALCORN_CONTROL_TOKEN").ok();
    let client_name = env::var("FALCORN_CONTROL_CLIENT").ok();

    let mut builder = ControlClient::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);
    }

    let mut client = builder.connect()?;

    match action.as_str() {
        "status" => {
            let status = client.get_status()?;
            println!("{:#?}", status);
        }
        "workers" => {
            let workers = client.get_workers()?;
            println!("{:#?}", workers);
        }
        "show-config" => {
            let config = client.show_config()?;
            println!("{}", config);
        }
        "scale" => {
            let workers = args
                .next()
                .ok_or("scale requires worker count")?
                .parse::<usize>()?;
            let message = client.scale_to(workers)?;
            println!("{}", message);
        }
        "restart" => {
            let id = args.next().and_then(|value| value.parse::<u32>().ok());
            let force = args.any(|value| value == "--force");
            let message = client.restart_worker(id, !force)?;
            println!("{}", message);
        }
        "shutdown" => {
            let force = args.any(|value| value == "--force");
            let message = client.shutdown(!force)?;
            println!("{}", message);
        }
        "reload" => {
            let mut path = None;
            let mut rolling = true;
            for value in args {
                if value == "--no-rolling" {
                    rolling = false;
                } else if value.starts_with("--path=") {
                    path = value.split('=').nth(1).map(|s| s.to_string());
                } else if path.is_none() {
                    path = Some(value);
                }
            }
            let message = client.reload_config(path, rolling)?;
            println!("{}", message);
        }
        other => {
            eprintln!(
                "Unknown action: {} (use status|workers|show-config|scale|restart|shutdown|reload)",
                other
            );
        }
    }

    Ok(())
}
