"""Enumerate small navigation tasks; write one CSV row per layout and policy."""
import argparse
import csv
from collections import deque
from itertools import combinations
import sys

WIDTH, HEIGHT = 7, 5
START, GOAL = (0, 2), (6, 2)
DIRECTIONS = ((1, 0), (0, -1), (0, 1), (-1, 0))


def neighbors(position, gaps):
    x, y = position
    for dx, dy in DIRECTIONS:
        nx, ny = x + dx, y + dy
        if 0 <= nx < WIDTH and 0 <= ny < HEIGHT and (nx != 3 or ny in gaps):
            yield nx, ny


def distances_to_goal(gaps):
    distance = {GOAL: 0}
    queue = deque([GOAL])
    while queue:
        current = queue.popleft()
        for neighbor in neighbors(current, gaps):
            if neighbor not in distance:
                distance[neighbor] = distance[current] + 1
                queue.append(neighbor)
    return distance


def manhattan(position):
    return sum(abs(a - b) for a, b in zip(position, GOAL))


def run(gaps, budget, distance):
    position = START
    for moves in range(budget + 1):
        if position == GOAL:
            return "goal", moves
        if moves == budget:
            return "cutoff", moves
        options = [n for n in neighbors(position, gaps) if distance(n) < distance(position)]
        if not options:
            return "stalled", moves
        position = min(options, key=distance)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--gaps", type=int, choices=(0, 1, 2), default=1)
    parser.add_argument("--budget", type=int, default=12, help="maximum moves per episode")
    args = parser.parse_args()
    if args.budget < 0:
        parser.error("budget must be nonnegative")
    rows = csv.writer(sys.stdout, lineterminator="\n")
    rows.writerow(["gap_rows", "shortest_path", "policy", "outcome", "moves"])
    for gaps in combinations(range(HEIGHT), args.gaps):
        distance = distances_to_goal(gaps)
        for name, metric in (("greedy", manhattan), ("planner", lambda n: distance.get(n, float("inf")))):
            outcome, moves = run(gaps, args.budget, metric)
            rows.writerow(["+".join(map(str, gaps)) or "none", distance.get(START, "unreachable"),
                           name, outcome, moves])


if __name__ == "__main__":
    main()
