#!/bin/env -S deno run -A

import { enumerate, range, to_int } from "./utils.ts";

function main() {
	const max_in_group = 4;
	const input = read_input("./input.csv");
	const groups = group_inputs(input, max_in_group);
	write_to_csv("./output.csv", groups);
}

function read_input(path: string) {
	const content = Deno.readTextFileSync(path);
	const cells = content.split("\n").filter((line) => line !== "").map((line) => line.split("\t"));
	const result = members_from_cells(cells);
	return result;
}

export type Memeber = ReturnType<typeof members_from_cells>[0];
export function members_from_cells(cells: string[][]) {
	return cells.map((
		[login, s1, s2, s3, s4, s5, s6],
	) => ({ login, choices: ([s1, s2, s3, s4, s5, s6] as const).map(to_int), placed: false }));
}

export type Group = ReturnType<typeof group_inputs>[0];
export function group_inputs(input: Memeber[], max_in_group: number) {
	const groups = range(1, 7)
		.arr()
		.map((sujet_no) => ({ sujet_no, members: [] as { login: string; prio: number }[] }));

	for (const prio of range(1, 7)) {
		for (const entry of input) {
			if (entry.placed) continue;
			for (const [index, choice] of enumerate(entry.choices)) {
				if (choice !== prio) continue;
				if (groups[index].members.length >= max_in_group) continue;
				groups[index].members.push({ login: entry.login, prio });
				entry.placed = true;
			}
		}
	}
	return groups;
}

export function groups_to_cells(groups: Group[]) {
	return groups.map(({ sujet_no, members }) => [
		`Sujet ${sujet_no}`,
		...members.map(({ login, prio }) => `${prio} ${login}`),
	]);
}

export function write_to_csv(path: string, groups: Group[]) {
	const result = groups_to_cells(groups).map((line) => line.join("\t")).join("\n");
	Deno.writeTextFileSync(path, result);
}

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