use std::path::PathBuf;

mod app;
mod dictionary;
mod md;
mod text;
mod utils;

fn main() -> eyre::Result<()> {
	let mut args = pico_args::Arguments::from_env();

	let dictionary: Option<String> = args
		.opt_value_from_str(["-d", "--dict"])?
		.or(std::env::var("HOOPOE_DEFAULT_DICT").ok());

	let cmd = args.subcommand()?;
	let file_path = match cmd.as_deref() {
		Some("dict") => {
			dictionary::dicts_cmd(args)?;
			std::process::exit(0);
		}
		Some(file_path) if PathBuf::from(file_path).is_file() => PathBuf::from(file_path),
		Some(file_path) if !PathBuf::from(file_path).is_file() => {
			eprintln!("unrecognized file: {file_path}");
			print_help(1)
		}

		Some("help") => print_help(0),
		None if args.contains(["-h", "--help"]) => print_help(0),
		None if args.contains(["-V", "--version"]) => print_version(0),
		_ => print_help(1),
	};

	app::run(&file_path, dictionary.as_deref())
}

fn print_version(code: i32) -> ! {
	let version = env!("CARGO_PKG_VERSION");
	eprintln!("{version}");
	std::process::exit(code);
}

fn print_help(code: i32) -> ! {
	eprintln!("{HELP_TEXT}");
	std::process::exit(code);
}

static HELP_TEXT: &str = "
hoopoe \u{13159}: spelling checker
	I have known what you have not and have come to you with spelling corrections.

USAGE:
	hoopoe [OPTIONS] <COMMAND>

COMMANDS:
	<FILE>        manage spelling mistakes in a TUI
	dict          manage installed dictionaries


OPTIONS:
	-d, --dict <DICT> choose dictionary [env: HOOPOE_DEFAULT_DICT]
	-h, --help        display this message
	-V, --version     display version
";
