use super::RezonCommand;
use crate::{config::rezon_config::RezonConfig, tui::clean_console};
use async_trait::async_trait;
use clap::{ArgMatches, Command};
use colorful::{Color, Colorful};
use std::{fs::File, io::Write, path::Path, process::exit};

pub struct Init {}

#[async_trait]
impl RezonCommand for Init {
	fn cmd() -> clap::Command {
		Command::new("init").about("Initialize Rezon in an existing project!")
	}

	async fn execute(_: Option<RezonConfig>, _: ArgMatches) -> Result<(), crate::cli::CliError<'static>> {
		create_rezon_config_file();
		Ok(())
	}
}

pub fn create_rezon_config_file() {
	let file_name = "rezon.toml";
	let file_content = r#"[config]
api_key = "your_api_key_here"

[model]
h5_file = "/path/to/h5_file_model1.h5"
json_path = "/path/to/json_file_model.json"
parameters = ["name1", "name2", "name3"]
"#;

	let path = Path::new(file_name);
	if path.exists() {
		println!(
			"{} {}",
			file_name,
			"already exists in the current working directory!".color(Color::Red).bold()
		);
		exit(64);
	}

	let mut file = File::create(path).expect("Error: could not create rezon config file!");
	file.write_all(file_content.as_bytes())
		.expect("Error: could not scaffold rezon config file!");

	clean_console();

	println!(
		"{} Successfuly Initialized {}\n",
		"✓".color(Color::Green),
		"Rezon!".color(Color::Purple1a).bold()
	);
	println!(
		"{}{}{}{}",
		"Next steps:\n".color(Color::White).bold(),
		format!(
			"{} Add your Rezon API key to the newly created {} file\n",
			"➜".color(Color::Purple1a),
			"rezon.toml".color(Color::Purple1a).bold()
		),
		format!("{} Configure your model paths for deployment\n", "➜".color(Color::Purple1a)),
		format!(
			"{} Deploy your model to the cloud with `{} {}`\n",
			"➜".color(Color::Purple1a),
			"rezon".color(Color::Purple1a).bold(),
			"deploy".bold()
		)
	);
}
