package day03

import (
	"adventofcode2024/utils"
	"fmt"
	"regexp"
)

func Part1(input string) int {
	val := 0

	pattern := `mul\((\d{1,3}),(\d{1,3})\)`
	re := regexp.MustCompile(pattern)
	matches := re.FindAllStringSubmatch(input, -1)

	fmt.Println("Matches found:")
	for _, match := range matches {
		if len(match) == 3 { // match[1] is x, match[2] is y
			x := utils.MustAtoi(match[1])
			y := utils.MustAtoi(match[2])
			val += x * y
		}
	}
	return val
}

func Part2(input string) int {
	val := 0
	pattern := `mul\((\d{1,3}),(\d{1,3})\)`
	re := regexp.MustCompile(pattern)
	matches := re.FindAllStringSubmatchIndex(input, -1)

	fmt.Println("Matches found:")
	for _, match := range matches {
		if len(match) == 6 { 
			xStart, xEnd := match[2], match[3]
			yStart, yEnd := match[4], match[5]
			x := utils.MustAtoi(input[xStart:xEnd])
			y := utils.MustAtoi(input[yStart:yEnd])
			if do(input[:xStart]) {
				val += x * y
			}
		}
	}
	return val
}

func do(input string) bool {
	pattern := `don't\(\)|do\(\)`
	re := regexp.MustCompile(pattern)

	matches := re.FindAllString(input, -1)

	if len(matches) > 0 {
		// Get the last match
		lastMatch := matches[len(matches)-1]
		if lastMatch == "don't()" {
			return false
		} else if lastMatch == "do()" {
			return true
		}
	}
	return true
}
