use std::collections::HashMap;

use ability::Ability;
use askama::Template;
use command::Command;
use finisher::Finisher;
use itertools::Itertools;
use serde::Deserialize;

use crate::{RuntimeModule, create_file};

mod ability;
mod command;
mod finisher;
mod melding;

const ABILITIES_PATH: &str = "./input/bbs/abilities.json";
const FINISHERS_PATH: &str = "./input/bbs/finish-commands.json";
const COMMANDS_PATH: &str = "./input/bbs/commands.json";

#[derive(Debug, Deserialize, PartialEq, Eq)]
enum Character {
	#[serde(alias = "A")]
	Aqua,
	#[serde(alias = "V")]
	Ventus,
	#[serde(alias = "T")]
	Terra,
}

#[derive(Template)]
#[template(path = "pages/bbs/melding.html")]
struct CommandsTemplate {
	pub commands: Vec<Command>,
	pub crystals: Vec<String>,
}

pub struct Module;

impl RuntimeModule for Module {
	fn start_module() {
		tracing::info!("Loading BBS abilities data from {}", ABILITIES_PATH);
		let abilities_str = std::fs::read_to_string(ABILITIES_PATH).unwrap();
		let abilities = serde_json::from_str::<Vec<Ability>>(&abilities_str).unwrap();

		tracing::info!("Loading BBS finishers data from {}", ABILITIES_PATH);
		let finishers_str = std::fs::read_to_string(FINISHERS_PATH).unwrap();
		let finishers = serde_json::from_str::<HashMap<String, Finisher>>(&finishers_str).unwrap();

		tracing::info!("Loading BBS commands data from {}", ABILITIES_PATH);
		let commands_str = std::fs::read_to_string(COMMANDS_PATH).unwrap();
		let mut commands = serde_json::from_str::<Vec<Command>>(&commands_str).unwrap();

		// Create a vec with all the crystal variants found in abilities
		let crystals = abilities
			.iter()
			.map(|x| x.from.clone())
			.unique()
			.sorted()
			.collect();

		// Create a vec of crystals and what ability they give for each recipe
		for cmd in commands.iter_mut() {
			for recipe in cmd.recipes.iter_mut() {
				recipe.set_abilities(&abilities);
			}
		}

		tracing::info!("Generating BBS melding table template");
		let melding_template = CommandsTemplate { commands, crystals };

		create_file("./out/bbs", "melding", melding_template).unwrap();
	}
}
