use anyhow::Result;
use clap::Parser;
use llamastash::{
  cli::{self, Cli},
  config::loader,
  util::logging,
};

#[tokio::main]
async fn main() -> Result<()> {
  // Translate `LLAMASTASH_OFFLINE=1`/`0`/empty into the `true`/unset clap's
  // boolean env binding accepts, before parsing argv (see the fn doc).
  cli::cli_args::normalize_offline_env();

  // Parse by hand so clap's arg-rejection exit code matches our contract:
  // a usage error exits USAGE (64), not clap's default 2. `--help` /
  // `--version` are not errors — clap writes them to stdout and we exit 0.
  let cli = match Cli::try_parse() {
    Ok(cli) => cli,
    Err(err) => {
      let _ = err.print();
      let code = if err.use_stderr() {
        cli::exit_codes::USAGE
      } else {
        0
      };
      std::process::exit(code);
    }
  };

  // Logger must be initialised BEFORE the panic hook — `log::error!` inside
  // the hook is a silent no-op while no logger is registered, so a panic
  // during CLI parsing/early startup would otherwise leave no trace in the
  // log file. Both calls are best-effort: a missing log dir or an already
  // initialised logger shouldn't block CLI use.
  let _ = logging::init(cli.verbose);
  logging::install_panic_hook();

  let config = loader::load_config(cli.config.clone());
  let code = cli::dispatch(cli, config).await?;
  std::process::exit(code);
}
