export class Dict {
	words;
	letters;
	length;

	constructor(words: Set<string>, length: number) {
		this.words = words;
		this.length = length;
		this.letters = new Set([...words.values()].map((w) => w.split("")).flat());
	}

	static async from_file(path: string, length: number) {
		const words = new Set<string>();
		const content = await Deno.readTextFile(path);
		for (const word of content.split("\n")) {
			const word_ = word.trim().toLowerCase();
			if (word_.length !== length) continue;
			if (contains_any(word_, [" ", "-", "."])) continue;
			words.add(remove_accents(word_));
		}
		return new Dict(words, length);
	}

	[Symbol.for("Deno.customInspect")]() {
		return `Dict { ${this.words.size} words }`;
	}
}

export function contains_any(text: string, words: string[]) {
	for (const word of words) if (text.includes(word)) return true;
	return false;
}

export function remove_accents(text: string) {
	const accents = [
		...[["à", "a"], ["â", "a"], ["ä", "a"]],
		...[["ç", "c"]],
		...[["é", "e"], ["è", "e"], ["ê", "e"], ["ë", "e"]],
		...[["î", "i"], ["ï", "i"]],
		...[["ô", "o"], ["ö", "o"]],
		...[["û", "u"]],
	];
	let result = text;
	for (const [accent, alternative] of accents) result = result.replaceAll(accent, alternative);
	return result;
}
