use std::fmt::Display;

use rinja::Template;
use serde::Deserialize;

use crate::create_file;

#[derive(Debug, Deserialize, PartialEq, Eq)]
struct Recipes {
	starters: Vec<Recipe>,
	soups: Vec<Recipe>,
	fish: Vec<Recipe>,
	meat: Vec<Recipe>,
	deserts: Vec<Recipe>,
}

#[derive(Debug, Deserialize, PartialEq, Eq)]
struct Recipe {
	name: String,
	is_special: bool,
	ingredients: Vec<String>,
	normal: FoodStats,
	plus: FoodStats,
}

impl Recipe {
	fn stats(&self, is_plus: &bool) -> &FoodStats {
		if *is_plus {
			&self.plus
		} else {
			&self.normal
		}
	}
}

#[derive(Debug, Deserialize, PartialEq, Eq)]
struct FoodStats {
	str: u8,
	mag: u8,
	def: u8,
	hp: u8,
	mp: u8,
}

impl Display for FoodStats {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		let val = serde_json::json!({
			"str": self.str,
			"mag": self.mag,
			"def": self.def,
			"hp": self.hp,
			"mp": self.mp
		});
		f.write_str(&val.to_string())?;
		Ok(())
	}
}

#[derive(Template)]
#[template(path = "pages/kh3/food-sim.html")]
struct RecipesTemplate {
	pub recipes: Recipes,
}

const RECIPES_PATH: &str = "./input/kh3/recipes.toml";

pub fn init() {
	tracing::info!("Loading recipes data from {}", RECIPES_PATH);
	let recipes_str = std::fs::read_to_string(RECIPES_PATH).unwrap();
	let recipes = toml::from_str::<Recipes>(&recipes_str).unwrap();

	tracing::info!("Generating the KH3 recipes template");
	let food_template = RecipesTemplate { recipes };

	create_file("./out/kh3", "food-sim", food_template.render().unwrap()).unwrap();
}
