package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"
)

const PIVOT = 25

func main() {
	if err := realMain(); err != nil {
		log.Println(err)
	}
}

func realMain() error {
	data, err := parseInput()
	if err != nil {
		return err
	}
	p1, err := SolveFirst(data)
	if err != nil {
		return err
	}
	log.Println("Part1:", p1)

	p2, err := SolveSecond(data, p1)
	if err != nil {
		return err
	}
	log.Println("Part2:", p2)

	return nil
}

func SolveFirst(data []int) (int, error) {
	for i, d := range data {
		if i < PIVOT+2 {
			continue
		}
		if !sum(data, i, d) {
			return d, nil
		}
	}
	return 0, fmt.Errorf("invalid not found")
}

func SolveSecond(data []int, invalid int) (int, error) {
	for i, d := range data {
		var sum = d
		var min, max = d, d
		for j := i + 1; j < len(data); j++ {
			sum += data[j]
			if data[j] < min {
				min = data[j]
			}
			if data[j] > max {
				max = data[j]
			}
			if sum == invalid {
				return min + max, nil
			}
			if sum > invalid {
				break
			}
		}
	}
	return 0, fmt.Errorf("sum for invalid not found")
}

// XXX sort!
func sum(data []int, idx int, val int) bool {
	for i := idx - PIVOT - 1; i <= idx; i++ {
		for j := idx - PIVOT - 2; j <= idx; j++ {
			if data[i]+data[j] == val {
				return true
			}
		}
	}
	return false
}

func parseInput() ([]int, error) {
	fd, err := os.Open("input.txt")
	if err != nil {
		return nil, err
	}
	defer fd.Close()

	var ret []int

	buf := bufio.NewScanner(fd)
	for buf.Scan() {
		tmp, err := strconv.Atoi(buf.Text())
		if err != nil {
			return nil, err
		}
		ret = append(ret, tmp)
	}

	return ret, nil
}