use clap::Parser;
use config::AppConfig;
use observability::init_tracing_subscriber;

#[derive(Parser, Debug)]
#[command(name = "gitserver")]
#[command(version)]
struct Args {
    #[arg(long, default_value = "info")]
    log_level: String,
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let args = Args::parse();
    let cfg = AppConfig::load();
    init_tracing_subscriber(&args.log_level, false);

    let http_handle = tokio::spawn(git::http::run_http(cfg.clone()));
    let ssh_handle = tokio::spawn(git::ssh::run_ssh(cfg));

    tokio::select! {
        result = http_handle => {
            match result {
                Ok(Ok(())) => tracing::info!("HTTP server stopped"),
                Ok(Err(e)) => tracing::error!("HTTP server error: {}", e),
                Err(e) => tracing::error!("HTTP server task panicked: {}", e),
            }
        }
        result = ssh_handle => {
            match result {
                Ok(Ok(())) => tracing::info!("SSH server stopped"),
                Ok(Err(e)) => tracing::error!("SSH server error: {}", e),
                Err(e) => tracing::error!("SSH server task panicked: {}", e),
            }
        }
        _ = tokio::signal::ctrl_c() => {
            tracing::info!("received shutdown signal");
        }
    }

    tracing::info!("shutting down");
    Ok(())
}
