import re
import sys
import math
import os
sys.path.insert(1, os.path.abspath('../../'))
from python_tools.aoc_utils import *

START = [0,0]
# INPUTS = ["test.txt", [6,6], 12]
INPUTS = ["input.txt", [70,70,], 1024]
END = INPUTS[1]

def grid_check(x, i):
    global END
    return ((0 <= x[0] <= END[0]) and (0 <= x[1] <= END[1]) and (x not in i))

def part_one(input):
    add = lambda x,y: [x[0]+y[0], x[1]+y[1]]
    sub = lambda x,y: [x[0]-y[0], x[1]-y[1]]
    mag = lambda x: math.sqrt(x[0]**2 + x[1]**2)
    p = [0,0]
    G = {}
    V = set()
    V.add(tuple(p))
    G[tuple([mag(sub(END, p)), *p])] = [p]
    while len(G)>0:
        keys = list(G.keys())
        keys.sort()
        p_list = G.pop(keys[0])
        p = p_list[-1]
        for x in [[1,0],[-1,0],[0,1],[0,-1]]:
            nx = add(x,p)
            if nx == END:
                return len(p_list)
            if grid_check(nx, input) and tuple(nx) not in V:
                h = tuple([mag(sub(END, nx)), *nx])
                V.add(tuple(nx))
                G[h] = [*p_list, nx]
    return -1

def part_two(input):
    result = 0
    upper = len(input)
    lower = INPUTS[2]
    while upper != lower:
        test = int(round((upper - lower+0.001)/2))+lower
        result = part_one(input[:test])
        if result == -1:
            upper = test-1
        else:
            lower = test
    print("P2: ", str(input[lower]).strip('[]').replace(" ", ""))


def main():
    f = open(INPUTS[0], 'r')
    contents = [list(map(int, x.strip().split(","))) for x in f.readlines()]
    print("P1: ", part_one(contents[:INPUTS[2]]))
    part_two(contents)

if __name__ == "__main__":
    main()