#!/usr/bin/env -S deno run --allow-read

import { Command } from "https://deno.land/x/cliffy@v1.0.0-rc.4/command/mod.ts";
import { Dict, GameLogging, InputGuesser, Runner, Simulator } from "./lib/lib.ts";
import { gutenberg } from "../data/data.ts";
import { range } from "./lib/utils.ts";

async function main() {
	const args = await new Command().name("simulation")
		.description(
			"Program to simulate TUSMO game with guesser controller.",
		)
		.option(
			"-f, --file <path:string>",
			"Sets dictionnary to use words from (defaults to internal french dict).",
		).option(
			"-l, --length <length:number>",
			"Length of the word to use from the dictionnary.",
		).option(
			"-n, --iterations <iterations:number>",
			"Number of iterations.",
		).option(
			"-t, --target <target:string>",
			"Target word to search for.",
		).parse(Deno.args);

	const length = args.options.length ?? args.options.target?.length ?? 6;

	let dict = Dict.from_lines(gutenberg, length);
	if (args.options.file !== undefined) dict = await Dict.from_text_file(args.options.file, length);

	let game = Simulator.from_dict_rand(dict);
	if (args.options.target !== undefined) game = new Simulator(validate_target(args.options.target, length));

	const guesser = new InputGuesser(length);
	const runner = new Runner(game, guesser, new GameLogging());

	const iterations = args.options.iterations ?? 100_000;
	for (const _ of range(0, iterations)) await runner.play_once();
}

function validate_target(target: string, length: number) {
	if (target.length !== length) throw new Error("Invalid target length");
	return target.toLowerCase();
}

if (import.meta.main) await main();
