#![warn(clippy::all, clippy::pedantic)]
#![allow(clippy::missing_errors_doc)]

// Copyright (C) 2026 Ordinary Labs, LLC.
//
// SPDX-License-Identifier: AGPL-3.0-only

#[cfg(feature = "mimalloc")]
use mimalloc::MiMalloc;

#[cfg(feature = "mimalloc")]
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;

#[cfg(feature = "jemalloc")]
#[cfg(not(target_env = "msvc"))]
use tikv_jemallocator::Jemalloc;

#[cfg(feature = "jemalloc")]
#[cfg(not(target_env = "msvc"))]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;

#[allow(clippy::too_many_lines)]
#[tokio::main]
async fn main() -> anyhow::Result<()> {
    #[cfg(feature = "docs")]
    {
        use clap::{CommandFactory, ValueEnum};

        let markdown: String = clap_markdown::help_markdown::<ordinaryd::Cli>();
        std::fs::write(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs/cli-reference.md"),
            markdown,
        )?;

        let outdir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("generated");
        std::fs::create_dir_all(&outdir)?;

        let cmd = ordinaryd::Cli::command();
        clap_mangen::generate_to(cmd, &outdir)?;

        let mut cmd = ordinaryd::Cli::command();
        for &shell in clap_complete::Shell::value_variants() {
            clap_complete::generate_to(shell, &mut cmd, env!("CARGO_PKG_NAME"), &outdir)?;
        }
    }

    #[cfg(not(feature = "docs"))]
    {
        use clap::Parser;
        use ordinaryd::{run, setup};

        let cli = ordinaryd::Cli::parse();

        if tokio_rustls::rustls::crypto::ring::default_provider()
            .install_default()
            .is_err()
        {
            tracing::error!("failed to get rustls default provider");
        }

        let logs_dir = setup(&cli)?;
        run(&cli, &logs_dir.into_boxed_path()).await?;
    }

    Ok(())
}
