use std::{mem, process};

use guartcl::guardian_interp;
use jimtcl::{JimError, JimResult, cli::Jimsh};

use clap::{CommandFactory, FromArgMatches, Parser};

static GUARTCL_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Enhanced Jim Tcl shell, with Rust-based superpowers.
#[derive(Parser)]
#[command(version, name = "guarsh")]
struct GuardianShell {
    #[command(flatten)]
    jimsh: Jimsh,

    /// Parse command-line arguments with Usage.
    #[arg(short = 'U', long = "usage")]
    usage: bool,
}

fn main() -> JimResult<()> {
    let interp = guardian_interp()?;

    let cli = GuardianShell::command().long_version(format!(
        "{} (Jim version {})",
        GUARTCL_VERSION,
        interp.jim_version()?
    ));

    let cli = GuardianShell::from_arg_matches(&cli.get_matches())
        .map_err(|e| JimError::from(format!("CLI error: {}", e)))?;

    cli.jimsh.setup_env(&interp)?;
    if cli.usage
        && let Some(script) = cli.jimsh.script_file()
    {
        guartcl::usage::parse_args(&interp, script.as_ref(), &cli.jimsh.script)?;
    }
    let rc = cli.jimsh.run(&interp)?;
    mem::drop(interp);
    process::exit(rc);
}
