""" day_04_01.py """

# usage: python3 day_04_01.py


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

    return data


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


def access(pos, xs, grid):
    """ less than 4 neighbours """
    deltas = [(0, -1), (0, 1), (-1, 0), (1, 0),
              (-1, -1), (1, 1), (1, -1), (-1, 1)]

    count = 0
    y, x = divmod(pos, xs)
    for dx, dy in deltas:
        i = x + dx + (y + dy) * xs
        if grid.get(i, '.') == '@':
            count += 1

    return count < 4


def solve(data):
    """ solve the puzzle """
    rolls = {i: symbol for i, symbol in enumerate(data) if symbol == '@'}
    cols = data.find('\n') + 1

    return sum(1 for i in rolls if access(i, cols, rolls))


if __name__ == '__main__':
    test(get('example01'), 13)

    puzzle = get('input')
    solution = solve(puzzle)

    print(solution)
