package main

import (
	"AOC2021/src/helper"
	"fmt"
	"os"
	"sort"
)

func main() {
	args := os.Args[1:]
	input, err := helper.GetInput(args[0])
	if err != nil {
		fmt.Println(err)
	}
	pointsMapper := map[rune]int{')': 3, ']': 57, '}': 1197, '>': 25137}
	sumPart1 := 0
	sumsPart2 := make([]int,0)
	for _, row := range input {
		errorRune, restScore := checkRow(row)
		sumPart1 += pointsMapper[errorRune]
		if errorRune == ' ' {
			sumsPart2 = append(sumsPart2, restScore)
		}
	}
	fmt.Println(sumPart1)
	sort.Ints(sumsPart2)
	fmt.Println(sumsPart2[len(sumsPart2)/2])
}

func checkRow(row string) (errorRune rune, restScore int) {
	openChunks := make([]rune, 0)
	errorRune = ' '
	for _, char := range row {
		switch char {
		case '(', '[', '{', '<':
			openChunks = append(openChunks, char)
		case '>', ']', '}':
			if char != openChunks[len(openChunks)-1]+2 {
				errorRune = char
				return
			}
			openChunks = openChunks[:len(openChunks)-1]
		case ')':
			if char != openChunks[len(openChunks)-1]+1 {
				errorRune = char
				return
			}
			openChunks = openChunks[:len(openChunks)-1]
		}
	}
	restScore = caclulateScoreForIncompletePart(openChunks)
	return
}

func caclulateScoreForIncompletePart(openChunks []rune) int {
	pointsMapper := map[rune]int{'(': 1, '[': 2, '{': 3, '<': 4}
	sum := 0
	for i := len(openChunks)-1; i>= 0; i-- {
		pointForChar := pointsMapper[openChunks[i]]
		sum = sum * 5 + pointForChar
	}
	return sum
}
