import ast

#  y+-----------+
#  4|     1     |
#  3|   2 3 4   |
#  2| 5 6 7 8 9 |
#  1|   A B C   |
#  0|     D     |
#   +-----------+
#     0 1 2 3 4 x


KEYPAD = {
    '[2, 4]': '1',
    '[1, 3]': '2',
    '[2, 3]': '3',
    '[3, 3]': '4',
    '[0, 2]': '5',
    '[1, 2]': '6',
    '[2, 2]': '7',
    '[3, 2]': '8',
    '[4, 2]': '9',
    '[1, 1]': 'A',
    '[2, 1]': 'B',
    '[3, 1]': 'C',
    '[2, 0]': 'D'
}


def get_coordinates(value):  # get coordinates by value
    for key in KEYPAD.keys():
        if KEYPAD[key] == value:
            return key
    return None


def get_value(coordinates):  # get value by coordinates
    return KEYPAD[str(coordinates)]


def parse_line(start, line_data):
    # todo: fix borders (like part1)
    coordinates = ast.literal_eval(get_coordinates(start))
    for instruction in line_data:
        if instruction == "U":
            if coordinates not in [[0, 2], [1, 3], [2, 4], [3, 3], [4, 2]]:
                if coordinates[1] < 4:
                    coordinates[1] += 1  # Add 1 to y

        elif instruction == "D":
            if coordinates not in [[0, 2], [1, 1], [2, 0], [3, 1], [4, 2]]:
                if coordinates[1] > 0:
                    coordinates[1] -= 1  # Subtract 1 from y

        elif instruction == "L":
            if coordinates not in [[0, 2], [1, 3], [1, 1], [2, 4], [2, 0]]:
                if coordinates[0] > 0:
                    coordinates[0] -= 1  # Subtract 1 from x

        elif instruction == "R":
            if coordinates not in [[4, 2], [3, 3], [3, 1], [2, 4], [2, 0]]:
                if coordinates[0] < 4:
                    coordinates[0] += 1  # Add 1 to x

    result = get_value(coordinates)

    return result


def solve(puzzle_input):
    result = ""

    lines = puzzle_input.split("\n")
    start = "5"
    for line in lines:
        output = parse_line(start, line)
        result += output
        start = output

    return result


def main():
    f = open("puzzle_input")
    puzzle_input = f.read()
    f.close()

    solution = solve(puzzle_input)
    print(solution)

if __name__ == "__main__":
    main()

