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

use std::{fs, process::ExitCode};

use tracing_subscriber::EnvFilter;

use brew_proxy::client;
use brew_proxy_utils::{
    BREW_EXECUTABLE, BREW_PREFIX, BrewCommand, BusType, ENV_VAR_NONINTERACTIVE,
};

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

    if !matches!(fs::exists(BREW_EXECUTABLE), Ok(true)) {
        eprintln!("brew-proxy: Homebrew installation not detected at {BREW_PREFIX}");
        return ExitCode::FAILURE;
    }

    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!("{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 interactive_auth =
        !std::env::var(ENV_VAR_NONINTERACTIVE).is_ok_and(|s| !["", "0", "false"].contains(&&*s));

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