use crate::cmd::CliContext;
use crate::event;
use crate::output::OutFormat;
use clap::Parser;
use eternaltwin_core::types::WeakError;
use std::borrow::Cow;
use std::io::Write;

/// Arguments to the `version` task.
#[derive(Debug, Parser)]
pub struct Args {
  #[arg(long, value_enum, default_value_t)]
  format: OutFormat,
}

pub async fn run(mut cx: CliContext<'_, Args>) -> Result<(), WeakError> {
  let version = get_version();
  match cx.args.format {
    OutFormat::Json => {
      serde_json::to_writer_pretty(&cx.out, &version).expect("io write failed");
      cx.out.write_all(b"\n").expect("io write failed");
    }
    OutFormat::Jsonl => serde_json::to_writer(cx.out, &version).expect("io write failed"),
    OutFormat::Text => writeln!(cx.out, "eternaltwin {}", version.eternaltwin).expect("io write failed"),
  };
  Ok(())
}

pub fn get_version() -> event::Version {
  event::Version {
    eternaltwin: Cow::Borrowed(env!("CARGO_PKG_VERSION")),
  }
}
