package main

import (
	"fmt"
	"strings"

	h "git.bullercodeworks.com/brian/adventofcode/helpers"
)

func main() {
	inp := h.StdinToStringSlice()[0]
	fishStr := strings.Split(inp, ",")
	part1(fishStr)
	part2(fishStr)
}

func part1(fishStr []string) {
	var fish []int
	for i := range fishStr {
		fish = append(fish, h.Atoi(fishStr[i]))
	}
	for i := 0; i < 80; i++ {
		var newFish int
		for l := range fish {
			if fish[l] == 0 {
				fish[l] = 6
				newFish++
			} else {
				fish[l]--
			}
		}
		for ; newFish > 0; newFish-- {
			fish = append(fish, 8)
		}
	}
	fmt.Println()
	fmt.Println("# Part 1")
	fmt.Println(len(fish), "fish")
	fmt.Println()
}

// For 256 days there are too many to do it the same way. Instead we track the number of fish per cycle
func part2(fishStr []string) {
	var fish []int
	for i := range fishStr {
		fish = append(fish, h.Atoi(fishStr[i]))
	}
	fishMap := make(map[int]int)
	for i := 0; i < 9; i++ {
		fishMap[i] = 0
	}
	for i := range fish {
		fishMap[fish[i]]++
	}

	for i := 0; i < 256; i++ {
		zeros := fishMap[0]
		fishMap[0] = fishMap[1]
		fishMap[1] = fishMap[2]
		fishMap[2] = fishMap[3]
		fishMap[3] = fishMap[4]
		fishMap[4] = fishMap[5]
		fishMap[5] = fishMap[6]
		fishMap[6] = fishMap[7] + zeros
		fishMap[7] = fishMap[8]
		fishMap[8] = zeros
	}
	fmt.Println()
	fmt.Println("# Part2")
	total := 0
	for k := range fishMap {
		total += fishMap[k]
	}
	fmt.Println(total, "fish")
}

func printStatus(fish map[int]int) {
	var total int
	for i := 0; i < 8; i++ {
		fmt.Printf("[%d: %d] ", i, fish[i])
		total += fish[i]
	}
	fmt.Println("Total:", total)
}
