package day08

import (
	_ "fmt"

	"adventofcode2022/utils"
	"adventofcode2022/utils/inputs"
	"adventofcode2022/utils/grid2d"
)

func Part1(input string) int {
	grid := inputs.ToGrid2D(input, "\n", "", -1, utils.MustAtoi)
	visible := grid2d.NewGrid(grid.SizeX(), grid.SizeY(), false)

	for j := 0; j < grid.SizeY(); j++ {
		for i := 0; i < grid.SizeX(); i++ {
			directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
			for _, dir := range directions {
				v := true
				x := i
				y := j
				for {
					x += dir[0]
					y += dir[1]
					if x < 0 || x >= grid.SizeX() || y < 0 || y >= grid.SizeY() {
						break
					}
					if grid.Get(i, j) <= grid.Get(x, y) {
						v = false
						break
					}
				}
				if v {
					visible.Set(i, j, true)
					break
				}
			}
		}
	}

	sum := 0
	for j := 0; j < visible.SizeY(); j++ {
		for i := 0; i < visible.SizeX(); i++ {
			if visible.Get(i, j) {
				sum++
			}
		}
	}
	return sum
}

func Part2(input string) int {
	grid := inputs.ToGrid2D(input, "\n", "", -1, utils.MustAtoi)
	scenicScore := grid2d.NewGrid(grid.SizeX(), grid.SizeY(), 1)

	for j := 0; j < grid.SizeY(); j++ {
		for i := 0; i < grid.SizeX(); i++ {
			directions := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
			for _, dir := range directions {
				score := 0
				x := i
				y := j
				for {
					x += dir[0]
					y += dir[1]
					if x < 0 || x >= grid.SizeX() || y < 0 || y >= grid.SizeY() {
						break
					}
					if grid.Get(i, j) <= grid.Get(x, y) {
						score++
						break
					}
					score++
				}
				scenicScore.Set(i, j, scenicScore.Get(i,j) * score)
				}
		}
	}
	
	max := 0
	for j := 0; j < scenicScore.SizeY(); j++ {
		for i := 0; i < scenicScore.SizeX(); i++ {
			if scenicScore.Get(i, j) > max {
				max = scenicScore.Get(i, j)
			}
		}
	}
	return max
}
