package day01

import (
	"adventofcode2023/utils"
	 "fmt"
	"strings"
)
func Part1(input string) int {
	num := 0
	lines := strings.Split(input, "\n")
	for _, line := range lines {
		for i:=0;i<len(line);i++ {
			if line[i] >= '0' && line[i] <= '9' {
				num += utils.MustAtoi(string(line[i])) * 10
				break;
			}
		}
		for i:=len(line) - 1;i>=0;i-- {
			if line[i] >= '0' && line[i] <= '9' {
				num += utils.MustAtoi(string(line[i]))
				break;
			}
		}
	}
	return num
}


func Part2(input string) int {
	digits := make(map[string]string)
	digits["one"] = "1"
	digits["two"] = "2"
	digits["three"] = "3"
	digits["four"] = "4"
	digits["five"] = "5"
	digits["six"] = "6"
	digits["seven"] = "7"
	digits["eight"] = "8"
	digits["nine"] = "9"

	digits_backwards := make(map[string]string)
	digits_backwards["eno"] = "1"
	digits_backwards["owt"] = "2"
	digits_backwards["eerht"] = "3"
	digits_backwards["ruof"] = "4"
	digits_backwards["evif"] = "5"
	digits_backwards["xis"] = "6"
	digits_backwards["neves"] = "7"
	digits_backwards["thgie"] = "8"
	digits_backwards["enin"] = "9"
	
	num := 0
	found := false
	lines := strings.Split(input, "\n")
	for _, line := range lines {
		for i:=0;i<len(line);i++ {
			if line[i] >= '0' && line[i] <= '9' {
				fmt.Println("first digit:", string(line[i]))
				num += utils.MustAtoi(string(line[i])) * 10
				found = true
			}
			if found { break;}
			for key := range digits {
				if strings.HasPrefix(line[i:], key) {
					fmt.Println("first digit:", digits[key])
					num += utils.MustAtoi(digits[key]) * 10
					found = true
				}
				if found { break;}
			}
		}

		found = false

		reverse := reverseString(line)

		for i:=0;i<len(reverse);i++ {
			if reverse[i] >= '0' && reverse[i] <= '9' {
				fmt.Println("last digit:", string(reverse[i]))
				num += utils.MustAtoi(string(reverse[i]))
				found = true
			}
			if found { break;}
			for key := range digits_backwards {
				if strings.HasPrefix(reverse[i:], key) {
					fmt.Println("last digit:", digits_backwards[key])
					num += utils.MustAtoi(digits_backwards[key])
					found = true
				}
				if found { break;}
			}
		}
		found = false

	}
	return num
}

func reverseString(input string) string {
	// Convert the string to a rune slice
	runes := []rune(input)

	// Get the length of the rune slice
	length := len(runes)

	// Reverse the order of runes
	for i, j := 0, length-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}

	// Convert the reversed rune slice back to a string
	reversedString := string(runes)

	return reversedString
}