#!/usr/bin/env python3
"""Search a fixed, fully known grid with BFS/DFS; this does not map or drive a robot.
Original course teaching example. SPDX-License-Identifier: MIT.
"""
import argparse
from collections import deque
from common import output_dir, write_json

GRID = ("#########", "#S..#...#", "#.#.#.#.#", "#.#...#.#", "#.#####.#", "#......G#", "#########")
START, GOAL = (1, 1), (5, 7)
DIRECTIONS = ((0, 1), (1, 0), (0, -1), (-1, 0))  # right, down, left, up


def neighbors(grid, cell):
    for dr, dc in DIRECTIONS:
        row, col = cell[0] + dr, cell[1] + dc
        if 0 <= row < len(grid) and 0 <= col < len(grid[0]) and grid[row][col] != "#":
            yield (row, col)


def valid_path(grid, path, start, goal):
    return bool(path and path[0] == start and path[-1] == goal and
                all(0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] != "#" for r, c in path) and
                all(abs(a[0] - b[0]) + abs(a[1] - b[1]) == 1 for a, b in zip(path, path[1:])))


def search(grid, start, goal, kind):
    if kind not in ("bfs", "dfs"):
        raise ValueError("kind must be bfs or dfs")
    frontier = deque([start])
    parent = {start: None}  # Mark on insertion so each node is popped at most once.
    expanded = 0
    while frontier:
        cell = frontier.popleft() if kind == "bfs" else frontier.pop()
        expanded += 1
        if cell == goal:
            path = []
            while cell is not None:
                path.append(cell)
                cell = parent[cell]
            path.reverse()
            checked = valid_path(grid, path, start, goal)
            if not checked:
                raise AssertionError("Search returned an invalid path")
            return {"reached": True, "path": path, "path_length_edges": len(path) - 1,
                    "expanded_nodes": expanded, "path_valid": checked}
        choices = list(neighbors(grid, cell))
        # Reverse insertion preserves right/down/left/up visit priority for the stack.
        for neighbor in choices if kind == "bfs" else reversed(choices):
            if neighbor not in parent:
                parent[neighbor] = cell
                frontier.append(neighbor)
    return {"reached": False, "path": None, "path_length_edges": None,
            "expanded_nodes": expanded, "path_valid": None}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", required=True)
    parser.add_argument("--unreachable", action="store_true", help="Block the two neighbors of the goal")
    args = parser.parse_args()
    try:
        grid = list(GRID)
        if args.unreachable:
            for row, col in ((4, 7), (5, 6)):
                grid[row] = grid[row][:col] + "#" + grid[row][col + 1:]
        results = {kind: search(grid, START, GOAL, kind) for kind in ("bfs", "dfs")}
        out = output_dir(args.out)
        write_json(out / "paths.json", {
            "source": "synthetic_known_grid", "grid": grid, "start": START, "goal": GOAL,
            "coordinate_order": "[row, column], zero-based", "neighbor_order": "right, down, left, up",
            "unreachable_variant": args.unreachable, **results,
            "notes": ["Path length counts edges/moves, not cells. Each move costs one.",
                      "Expanded nodes count unique nodes removed from frontier, including goal if reached.",
                      "BFS finds a shortest path on this unit-cost known map. DFS need not be shortest.",
                      "Expanded nodes are computation, not robot travel or exploration. No mapping, odometry, localization or sim-to-real validation is included."]})
        print(f"BFS/DFS known-grid results written to {out}")
    except (OSError, ValueError) as exc:
        parser.error(str(exc))


if __name__ == "__main__":
    main()
