import { randomUUID } from "crypto";
import { shrinko8 } from "./shrinko8";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const outputDirPath = path.resolve(__dirname, "..", "..", "..", "output");

const getRom = async (inputFile: string) => {
	const uuid = randomUUID();
	const dir = path.join(outputDirPath, uuid);
	fs.mkdirSync(dir, {recursive: true});
	const outputFile = path.join(dir, "output.js");

	await shrinko8({
		inputFile,
		outputFile,
	});

	const js = await fs.promises.readFile(outputFile, "utf8");

	await fs.promises.rm(dir, {recursive: true, force: true});

	const match = js.match(/\b_cartdat\s*=\s*(\[.*?\])/s);
	if (!match) {
		console.log("BEGIN js contents --------------------------------------------");
		console.log(js);
		console.log("END js contents ----------------------------------------------");
		throw Error("Could not properly parse js file to find _cartdat");
	}

	return JSON.parse(match[1]) as number[]
}

const getCart = async (baseDir: string, inputFile: string) => {
	return {
		name: inputFile,
		rom: await getRom(path.join(baseDir, inputFile)),
	}
}

export const getCarts = async (baseDir: string, inputFiles: string[]) => {
	return await Promise.all(inputFiles.map(inputFile => getCart(baseDir, inputFile)));
}