import { readFileSync } from "fs"
import { argv, exit } from "process"
// too low 92772307
//
// too high 92949057
function second(input: number[]): void {
	const average = (input.reduce((a, x) => a += x) / input.length)
	console.log(`Average: ${average}`)
	console.log(`Summed Distance Rounded: ${input.map(x => increasingDistanceToAverage(x, Math.floor(average))).reduce((a, x) => a += x)}`)
	console.log(`Summed Distance +1: ${input.map(x => increasingDistanceToAverage(x, Math.floor(average) + 1)).reduce((a, x) => a += x)}`)
	console.log(`Summed Distance -1: ${input.map(x => increasingDistanceToAverage(x, Math.floor(average) - 1)).reduce((a, x) => a += x)}`)
}

function first(input: number[]): void {
	const med = findMedian(input.sort((a, b) => compareInt(a, b)))
	console.log(`Median: ${med}`)
	const distance = distanceToMedian(input, med)
	console.log(`Fuel: ${distance}`)
}
function increasingDistanceToAverage(input: number, average: number): number {
	const diff = difference(input, average)
	console.log(JSON.stringify(diff))
	return diff
}

function distanceToMedian(input: number[], median: number): number {
	let fuel = 0
	input.forEach(x => fuel += difference(x, median))
	return fuel
}
function findMedian(input: number[]): number {
	const length = input.length
	let location = Math.floor(length / 2)
	const value = input[location]
	return value
}

const difference = (a: number, b: number) => { return Math.abs(a - b) }

const compareInt = (a: number, b: number) => { return a - b }

function main(): void {
	if (argv[2] && argv[2] != "") {
		const values = readFileSync(argv[2], "utf8")
		const inputs = values.replace('\n', '').split(',').map(x => parseInt(x))
		first(inputs)
		second(inputs)
	} else {
		console.error("No filename")
		exit()
	}
}
main()
