use anyhow::Result;
use clap::Parser as _;
use dotenvy::dotenv;
use interim_models::MIGRATOR;
use tracing_subscriber::EnvFilter;

use crate::{
    app::App,
    cli::{Cli, Commands, serve_command, worker_command},
    settings::Settings,
};

mod app;
mod auth;
mod cli;
mod errors;
mod extractors;
mod field_info;
mod middleware;
mod navigator;
mod renderable_role_tree;
mod routes;
mod sessions;
mod settings;
mod user;
mod worker;
mod workspace_nav;
mod workspace_pooler;
mod workspace_user_perms;
mod workspace_utils;

/// Run CLI
#[tokio::main]
async fn main() -> Result<()> {
    // Attempt to pre-load .env in case it contains a RUST_LOG variable
    dotenv().ok();
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .init();

    let settings = Settings::load()?;

    let app = App::from_settings(settings.clone()).await?;

    if settings.run_database_migrations != 0 {
        MIGRATOR.run(&app.app_db).await?;
    }

    let cli = Cli::parse();
    match &cli.command {
        Commands::Serve => serve_command(app).await?,
        Commands::Worker(args) => worker_command(args, app).await?,
    }
    Ok(())
}
