import { assertExists } from "https://deno.land/std@0.224.0/assert/assert_exists.ts";

import { async_next, enumerate, LineReader, next } from "./utils.ts";

export async function initialize_prompt(lines: LineReader) {
	console.log("Please input initial state of the game. Format is :");
	console.log("  letter    [a-z]    known letter");
	console.log("  dot       .        unknown letter");
	console.log("example : .rb..");
	console.log("");
	const inputted = await parse_initialization_until_correct(lines);
	console.log("");
	console.log("From now on, please try the following guesses and report results. Format is :");
	console.log("  plus     +    correct");
	console.log("  minus    -    wrong placement");
	console.log("  dot      .    incorrect");
	console.log("example : -++..");
	console.log();
	return inputted;
}

async function parse_initialization_until_correct(lines: LineReader) {
	console.log("initial : ");
	while (true) {
		const input = await lines.read();
		assertExists(input);
		const parsed = parse_initialization(input);
		if (parsed !== null) return parsed;
		console.log("Invalid, please try again : ");
	}
}

function parse_initialization(input: string) {
	const code_a = "a".charCodeAt(0);
	const code_z = "z".charCodeAt(0);
	let length = 0;
	const constraints = [] as [number, string][];
	for (const [index, char] of enumerate(input.trim().toLowerCase())) {
		length += 1;
		if (char === ".") continue;
		const code = char.charCodeAt(0);
		if (code < code_a) return null;
		if (code > code_z) return null;
		constraints.push([index, char]);
	}
	return { length, constraints };
}
