use senl::{SenlApp, SenlError};
use std::{env, process};

fn main() {
    match run() {
        Ok(code) => process::exit(code),
        Err(SenlError::Cli(clap_err)) => clap_err.exit(),
        Err(e) => {
            eprintln!("senl: {e}");
            process::exit(1);
        }
    }
}

fn run() -> Result<i32, SenlError> {
    let raw_args: Vec<String> = env::args().collect();

    match raw_args.get(1).map(|s| s.as_str()) {
        Some("--help" | "-h") | None => {
            println!("usage: senl <app.lua> [command] [args...]");
            return Ok(0);
        }
        Some("--version" | "-V") => {
            println!("senl {}", env!("CARGO_PKG_VERSION"));
            return Ok(0);
        }
        _ => {}
    }

    let app_file = raw_args
        .get(1)
        .filter(|a| !a.starts_with('-'))
        .ok_or_else(|| {
            SenlError::App("unknown option; usage: senl <app.lua> [command] [args...]".into())
        })?;

    let remaining: Vec<&str> = raw_args.iter().skip(2).map(|s| s.as_str()).collect();
    SenlApp::from_file(app_file)?.run_with_args(remaining)
}
