package day_01

import "core:log"
import "core:os"
import "core:strconv"
import "core:strings"

Dir :: enum (u8) {
	Left  = 'L',
	Right = 'R',
}

Move :: struct {
	dir:   Dir,
	steps: int,
}

Input :: struct {
	moves: []Move,
}

Result1 :: int
Result2 :: int

// --- Input --- //
print_input :: proc(input: Input) {
	log.infof("%v", input)
}

parse_input_file :: proc(filepath: string) -> Input {
	input: Input

	raw_data, ok := os.read_entire_file_from_filename(filepath)
	if !ok {
		panic("oh no, could not read file")
	}
	defer delete(raw_data)

	lines, err := strings.split_lines(strings.trim_right_space(string(raw_data)))
	if err != .None {
		panic("oh no, failed splitting into lines")
	}
	defer delete(lines)

	i := 0
	input.moves = make([]Move, len(lines))
	for line in lines {
		input.moves[i] = {
			dir   = Dir(line[0]),
			steps = strconv.parse_int(line[1:]) or_else -1,
		}
		i += 1
	}

	return input
}

free_input :: proc(input: ^Input) {
	delete(input.moves)
	input.moves = nil
}
// --- Input --- //


// --- Helpers --- //
// --- Helpers --- //


// --- Task 1 --- //
run_task1 :: proc(input: Input) -> Result1 {
	result: Result1

	dial := 50
	for move in input.moves {
		dial = (dial + (move.steps if move.dir == .Right else -move.steps)) % 100
		for dial < 0 {
			dial += 100
		}

		log.debugf("dial: %d%s", dial, " HIT" if dial == 0 else "")
		if dial == 0 {
			result += 1
		}
	}

	return result
}

print_result1 :: proc(result: Result1) {
	log.infof("Task 1: %d", result)
}
// --- Task 1 --- //


// --- Task 2 --- //
run_task2 :: proc(input: Input) -> Result2 {
	result: Result2

	dial := 50
	for move in input.moves {
		new_dial := dial + (move.steps if move.dir == .Right else -move.steps)
		for new_dial < 0 {
			new_dial += 100
			result += 1
		}
		for new_dial > 99 {
			new_dial -= 100
			result += 1
		}

		dial = new_dial
		log.debugf("dial: %d => %d", dial, result)
	}

	return result
}

print_result2 :: proc(result: Result2) {
	log.infof("Task 2: %d", result)
}
// --- Task 2 --- //

run :: proc() {
	input := parse_input_file("input/day_01.txt")
	defer free_input(&input)

	result1 := run_task1(input)
	print_result1(result1)

	result2 := run_task2(input)
	print_result2(result2)
}