""" day_03_02.py """

# usage: python3 day_03_02.py


def get(filename):
    """ contents of filename """
    with open(filename, 'r', encoding='utf-8') as infile:
        data = infile.read().strip()

    return data


def square_sum(num):
    """ sum of adjacent squares """
    def neighbours_sum(i, j):
        """ sum of neighbours """
        k = [store.get((i + di, j + dj), 0)
             for di in [-1, 0, 1]
             for dj in [-1, 0, 1] if di != 0 or dj != 0]

        return sum(k)

    store = {(0, 0): 1}
    ring = 1

    x, y = 0, 0
    value = 1
    while num != value:
        ring += 2
        x = x + 1
        value += 1
        store[(x, y)] = neighbours_sum(x, y)

        for dx, dy in [(0, 1), (-1, 0), (0, -1), (1, 0)]:
            steps = ring - 1 if (dx, dy) != (0, 1) else ring - 2
            for _ in range(steps):
                if num == value:
                    return store[(x, y)]
                x, y = x + dx, y + dy
                value += 1
                store[(x, y)] = neighbours_sum(x, y)

    return store[(x, y)]


def test(data, solution):
    """ testing """
    output = solve(data)
    assert output == solution


def solve(data):
    """ solve the puzzle """
    square = int(data)
    return square_sum(square)


if __name__ == '__main__':
    test(get('example05'), 1)
    test(get('example06'), 1)
    test(get('example07'), 2)
    test(get('example08'), 4)
    test(get('example09'), 5)
    test(get('example10'), 806)

    puzzle = int(get('input'))

    y = 1
    while (x := solve(y)) < puzzle:
        y += 1

    print(x)
