// SPDX-FileCopyrightText: 2026 Contributors to brew-proxy <https://codeberg.org/HastD/brew-proxy>
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

use std::process::ExitCode;

use brew_proxy::client;
use brew_proxy_utils::{
    BrewCommand, BusType,
    env::{ENV_VAR_NONINTERACTIVE, ENV_VAR_TEST_PIPED, ENV_VAR_TEST_STDIN, env_var_set},
};
use tracing_subscriber::EnvFilter;

#[tokio::main]
async fn main() -> ExitCode {
    tracing_subscriber::fmt()
        .with_env_filter(EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .init();

    let mut argv = std::env::args();
    let cmd = match argv.nth(1).map(|s| s.parse::<BrewCommand>()) {
        Some(Ok(cmd)) => cmd,
        Some(Err(err)) => {
            let _ = client::print_usage(std::io::stderr());
            eprintln!("brew-proxy: {err}");
            return ExitCode::FAILURE;
        }
        None => {
            let _ = client::print_usage(std::io::stderr());
            return ExitCode::FAILURE;
        }
    };
    let args = Vec::from_iter(argv);

    if let Err(err) = client::print_brew_proxy_info(cmd, std::io::stderr()) {
        eprintln!("brew-proxy: {err}");
        return ExitCode::FAILURE;
    }

    let opts = client::ClientOptions {
        bus_type: BusType::Session,
        piped: env_var_set(ENV_VAR_TEST_PIPED),
        send_input: env_var_set(ENV_VAR_TEST_STDIN),
        interactive_auth: !env_var_set(ENV_VAR_NONINTERACTIVE),
    };

    match client::run(cmd, args, opts).await {
        Ok(exit_code) => exit_code,
        Err(err) => {
            println!("brew-proxy: {err}");
            ExitCode::FAILURE
        }
    }
}
