// Phonograph - A friendly PostgreSQL wrapper for nerds of all stripes.
// Copyright (C) 2025  Second System Technologies LLC
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.
//
// See the GNU Affero General Public License for more details. You should have
// received a copy of the GNU Affero General Public License along with this
// program.  If not, see <http://www.gnu.org/licenses/>.

use anyhow::Result;
use clap::Parser as _;
use phono_models::MIGRATOR;
use tracing_subscriber::EnvFilter;

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

mod app;
mod auth;
mod cli;
mod errors;
mod extractors;
mod field_info;
mod navigator;
mod permissions;
mod presentation_form;
mod routes;
mod sessions;
mod settings;
mod user;
mod worker;
mod workspace_nav;
mod workspace_pooler;
mod workspaces;

/// Run CLI
#[tokio::main]
async fn main() -> Result<()> {
    load_dotenv()?;

    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(())
}
