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

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

#[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::<ordinary::Cli>();

        let docs_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("docs");
        fs_err::create_dir_all(&docs_dir)?;

        fs_err::write(docs_dir.join("cli-reference.md"), markdown)?;

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

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

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

    #[allow(clippy::redundant_closure)]
    #[cfg(not(feature = "docs"))]
    {
        use clap::{CommandFactory, Parser};
        use ordinary::Commands;
        use ordinary::{run, setup};
        use ordinaryd::fmt::StdioLogFmt::Concise;
        use std::path::Path;

        clap_complete::CompleteEnv::with_factory(ordinary::Cli::command).complete();

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

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

        if let Commands::Start {
            mut app_api,
            mut global_args,
            disable_defaults,
        } = cli.commands
        {
            let project = cli.project.to_path_buf();

            let env_file = Path::new(&project).join(".env");
            if env_file.exists() {
                dotenv::from_path(env_file)?;
            }

            if !disable_defaults {
                app_api.insecure = true;
                app_api.insecure_cookies = true;

                global_args.stdio_logs = true;
                global_args.stdio_logs_fmt = Concise;
                global_args.log_sizes = true;
            }

            let cli = ordinaryd::Cli {
                commands: ordinaryd::Commands::App {
                    app_api,
                    project: project
                        .to_str()
                        .expect("failed to convert to string")
                        .to_string(),
                    domain_override: None,
                },
                global_args,
            };

            let logger = ordinaryd::setup(&cli)?;
            ordinaryd::run(&cli, logger).await?;
        } else {
            setup(&cli)?;
            run(&cli).await?;
        }
    }

    Ok(())
}
