package main

import (
	"AoC2020/helper"
	"fmt"
	"os"
	"regexp"
	"strings"
)

func main() {
	lineBreak := "\n"
	args := os.Args[1:]
	input, err := helper.GetFile(args[0])
	if err != nil {
		fmt.Println(err)
	}
	parsedInput := strings.Split(input, lineBreak+lineBreak)
	rulesInput := strings.Split(parsedInput[0], lineBreak)
	messagesInput := strings.Split(parsedInput[1], lineBreak)
	var rules = make(map[string]string)
	for _, val := range rulesInput {
		cleanS := strings.Replace(val, "\"","",-1)
		parsedRule := strings.Split(cleanS,": ")
		rules[parsedRule[0]] = parsedRule[1]
	}
	regex := getSummedRule(rules,"0")
	fmt.Println(regex)
	count := getValidMessages(regex, messagesInput)
	fmt.Println(count)
	rules["8"] = rules["8"] + " +"
	newRule11 := rules["11"]
	for i:= 0; i< 10; i++{
		newRule11 = "42 " + newRule11 + " 31"
		rules["11"] = rules["11"] + " | " + newRule11
	}
	regex = getSummedRule(rules,"0")
	fmt.Println(regex)
	count = getValidMessages(regex, messagesInput)
	fmt.Println(count)


}

func getValidMessages(regex string, messagesInput []string) int {
	r, _ := regexp.Compile("^" + regex + "$")
	count := 0
	for _, val := range messagesInput {
		if r.MatchString(val) {
			count++
		}
	}
	return count
}

func getSummedRule(rules map[string]string, rule string) string{
	r, _ := regexp.Compile("[0-9]")
	if rule == "+"{
		return rule
	}
	number := r.FindString(rules[rule])
	if number == "" {
		return rules[rule]
	}

	stringParts := strings.Split(rules[rule],"|")
	newRule := ""
	for _, val := range stringParts {
		newRule += "|"
		for _, s := range strings.Fields(val) {
			newRule += getSummedRule(rules,s)
		}
	}
	return "(" + newRule[1:] + ")"
}