//! Entrypoint for flora-cli
use anyhow::Result;
use omry_cli::ui::Ui;
use std::env;
use tracing::Level;
use tracing_subscriber::FmtSubscriber;

/// Default tracing level for omry-cli.
const DEFAULT_TRACING_LEVEL: Level = Level::ERROR;

/// The env var key for the tracing level.
const TRACING_LEVEL_KEY: &str = "OMRY_TRACING_LEVEL";

/// Gets the tracing level from the environment under [`TRACING_LEVEL_KEY`].
#[allow(clippy::print_stderr)]
fn tracing_level_from_env() -> Option<Level> {
    // Attempt to parse the tracing level we found in the environment,
    // or return None.
    env::var(TRACING_LEVEL_KEY).ok().and_then(|level| {
        level
            .parse::<Level>()
            .inspect_err(|e| eprintln!("Couldn't parse the value for {TRACING_LEVEL_KEY}: {e}"))
            .ok()
    })
}

#[tokio::main]
async fn main() -> Result<()> {
    let tracing_level = tracing_level_from_env().unwrap_or(DEFAULT_TRACING_LEVEL);
    let subscriber = FmtSubscriber::builder()
        .with_max_level(tracing_level)
        .finish();
    tracing::subscriber::set_global_default(subscriber)?;

    let mut ui = Ui::new().await?;
    ui.run_loop().await?;

    Ok(())
}
