#!/usr/bin/env node

const fs = require('node:fs')
const path = require('node:path')
const { parse } = require('yaml')

const ymlPath = path.join(__dirname, "..", "data", "spells.yml");
const data = parse(fs.readFileSync(ymlPath, "utf8"));

const columns = ["name", "cost", "targets", "duration"];

const myEscape = (s) =>
	String(s ?? "")
		.replace(/&/g, "&amp;")
		.replace(/</g, "&lt;")
		.replace(/>/g, "&gt;");

const generateTable = (spells, class_) => {
	const rows = spells
		.filter((elem) => elem.class === class_)
		.map(
			(spell) =>
				`  <tr>\n${columns.map((col) => `    <td>${myEscape(spell[col])}</td>`).join("\n")}\n  </tr><tr><td colspan="4">${spell["description"]}</td></tr>`,
		)
		.join("\n");

	const headers = columns
		.map((col) => `    <th>${col.charAt(0).toUpperCase() + col.slice(1)}</th>`)
		.join("\n");

	return `<table>
  <thead>
    <tr>
${headers}
    </tr>
  </thead>
  <tbody>
${rows}
  </tbody>
</table>
`;
};

["arcanist", "chimerist", "elementalist", "entropist", "spiritist"].forEach(
	(class_) => {
    process.stdout.write(`<h2>${class_} Spells</h2>\n`)
		process.stdout.write(generateTable(data.spells, class_));
	},
);
