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

import { group_inputs, members_from_cells, Memeber, write_to_csv } from "./converter.ts";
import { enumerate } from "./utils.ts";

async function main() {
	const sheet_id = "il9cnn4s9ugc";
	const sheet = await get_sheet(sheet_id);
	const members = extract_members(sheet, [0, 4]);
	const groups = group_inputs(members, 4);
	await write_to_csv("./output.csv", groups);
}

type Sheet = Awaited<ReturnType<typeof get_sheet>>;
async function get_sheet(sheet_id: string) {
	const response = await fetch(`https://ethercalc.net/${sheet_id}.csv`);
	const body = await response.text();
	return body.split("\n").map((line) => line.split(","));
}

function extract_members(sheet: Sheet, input_top_left: coords): Memeber[] {
	const [tl_x, tl_y] = input_top_left;
	const filtered = [] as string[][];
	for (const [y, line] of enumerate(sheet)) {
		if (y < tl_y) continue;
		const filtered_line = [] as string[];
		for (const [x, cell] of enumerate(line)) {
			if (x < tl_x) continue;
			filtered_line.push(cell);
		}
		filtered.push(filtered_line);
	}
	return members_from_cells(filtered);
}

type coords = [number, number];

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