use std::path::PathBuf;

use crate::ddd::ability::AbilityType;
use crate::{RuntimeModule, create_file};
use askama::Template;
use board::Board;

mod ability;
mod board;
mod board_position;
mod route;

const ABILITIES_PATH: &str = "./input/ddd/abilities";

#[derive(Template)]
#[template(path = "pages/ddd/boards.html")]
struct AbilitiesTemplate {
	pub boards: Vec<Board>,
}

pub struct Module;

impl RuntimeModule for Module {
	fn start_module() {
		tracing::info!("Loading DDD ability boards data from {}", ABILITIES_PATH);
		let mut boards: Vec<Board> = vec![];
		// Loading multiple files into one vector due to the size of each board
		let paths = std::fs::read_dir(ABILITIES_PATH)
			.unwrap()
			.filter_map(|f| f.ok())
			.map(|f| f.path())
			.filter_map(|p| match p.extension().is_some_and(|e| e == "toml") {
				true => Some(p),
				false => None,
			})
			.collect::<Vec<PathBuf>>();

		for path in paths {
			let board_str = std::fs::read_to_string(path).unwrap();
			let mut board = toml::from_str::<Board>(&board_str).unwrap();

			board.init_routes();
			board.init_total_lp();
			board.init_max_level();
			board.init_stats();
			board.init_ability_help();

			boards.push(board);
		}
		boards.sort_by(|a, b| a.order.cmp(&b.order));

		tracing::info!("Generating DDD ability boards template");
		let boards_template = AbilitiesTemplate { boards };

		create_file("./out/ddd", "boards", boards_template).unwrap();
	}
}
