# /// script
# requires-python = ">=3.11"
# dependencies = [
#     "marimo",
#     "numpy",
#     "matplotlib",
# ]
# ///

import marimo

__generated_with = "0.26.0"
app = marimo.App(width="medium")


@app.cell
def _():
    import heapq
    from collections import deque
    import marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return deque, heapq, mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 3.2: Grid Search and Graph Planning (BFS, Dijkstra, A*)

    Once a 2D map is sliced into an occupancy grid, graph search algorithms find collision-free paths from **Start** to **Goal**. Compare how **BFS**, **Dijkstra** (with obstacle-clearance costmap penalties), and **A\*** explore the exact same maze.
    """)
    return


@app.cell
def _(deque, heapq, np):
    def make_map(preset="u-trap", rows=14, cols=20):
        """Create a 2D boolean occupancy grid (True = wall)."""
        grid = np.zeros((rows, cols), dtype=bool)
        start = (rows // 2, 2)
        goal = (rows // 2, cols - 3)
        if preset == "u-trap":
            grid[3:11, 11] = True
            grid[3, 7:12] = True
            grid[10, 7:12] = True
        elif preset == "narrow-gap":
            grid[:, 9] = True
            grid[2, 9] = False
            grid[3:11, 14] = True
        grid[start] = False
        grid[goal] = False
        return grid, start, goal

    def build_costmap(grid, wall_penalty=0.35):
        """Inflate obstacle proximity into a soft traversal cost multiplier."""
        rows, cols = grid.shape
        cost = np.ones_like(grid, dtype=float)
        for r in range(rows):
            for c in range(cols):
                if grid[r, c]:
                    cost[r, c] = np.inf
                    continue
                for dr in (-1, 0, 1):
                    for dc in (-1, 0, 1):
                        nr, nc = r + dr, c + dc
                        if 0 <= nr < rows and 0 <= nc < cols and grid[nr, nc]:
                            cost[r, c] = 1.0 + wall_penalty
        return cost

    def search_grid(grid, start, goal, algo="A*", heuristic_weight=1.0):
        """Run BFS, Dijkstra, or A* on an 8-connected occupancy grid."""
        rows, cols = grid.shape
        costmap = build_costmap(grid)
        neighbors = [
            (0, 1, 1.0), (0, -1, 1.0), (1, 0, 1.0), (-1, 0, 1.0),
            (1, 1, np.sqrt(2.0)), (1, -1, np.sqrt(2.0)),
            (-1, 1, np.sqrt(2.0)), (-1, -1, np.sqrt(2.0)),
        ]
        explored = []
        parent = {}

        if algo == "BFS":
            q = deque([start])
            seen = {start}
            while q:
                curr = q.popleft()
                explored.append(curr)
                if curr == goal:
                    break
                r, c = curr
                for dr, dc, _step in neighbors:
                    nr, nc = r + dr, c + dc
                    if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr, nc]:
                        continue
                    if dr != 0 and dc != 0 and (grid[r, nc] or grid[nr, c]):
                        continue
                    nxt = (nr, nc)
                    if nxt not in seen:
                        seen.add(nxt)
                        parent[nxt] = curr
                        q.append(nxt)
        else:
            g_score = {start: 0.0}
            h0 = float(np.hypot(goal[0] - start[0], goal[1] - start[1])) if algo == "A*" else 0.0
            pq = [(heuristic_weight * h0, 0.0, start)]
            closed = set()
            while pq:
                _f, g, curr = heapq.heappop(pq)
                if curr in closed:
                    continue
                closed.add(curr)
                explored.append(curr)
                if curr == goal:
                    break
                r, c = curr
                for dr, dc, step in neighbors:
                    nr, nc = r + dr, c + dc
                    if not (0 <= nr < rows and 0 <= nc < cols) or grid[nr, nc]:
                        continue
                    if dr != 0 and dc != 0 and (grid[r, nc] or grid[nr, c]):
                        continue
                    nxt = (nr, nc)
                    if nxt in closed:
                        continue
                    tentative_g = g + step * costmap[nr, nc]
                    if tentative_g < g_score.get(nxt, np.inf):
                        g_score[nxt] = tentative_g
                        parent[nxt] = curr
                        h = float(np.hypot(goal[0] - nr, goal[1] - nc)) if algo == "A*" else 0.0
                        heapq.heappush(pq, (tentative_g + heuristic_weight * h, tentative_g, nxt))

        path = []
        if goal in parent or goal == start:
            cur = goal
            while cur != start:
                path.append(cur)
                cur = parent[cur]
            path.append(start)
            path.reverse()

        path_len = sum(
            float(np.hypot(path[i][0] - path[i - 1][0], path[i][1] - path[i - 1][1]))
            for i in range(1, len(path))
        )
        return explored, path, path_len

    return make_map, search_grid


@app.cell
def _(mo):
    algo_dd = mo.ui.dropdown(["BFS", "Dijkstra", "A*"], value="A*", label="Algorithm")
    map_dd = mo.ui.dropdown(["u-trap", "narrow-gap", "open"], value="u-trap", label="Map preset")
    weight_s = mo.ui.slider(0.5, 3.0, step=0.25, value=1.0, label="A* heuristic weight")

    mo.hstack([algo_dd, map_dd, weight_s], justify="start")
    return algo_dd, map_dd, weight_s


@app.cell
def _(algo_dd, make_map, map_dd, mo, np, plt, search_grid, weight_s):
    _grid, _start, _goal = make_map(map_dd.value)
    _explored, _path, _plen = search_grid(
        _grid, _start, _goal, algo=algo_dd.value, heuristic_weight=weight_s.value
    )

    _canvas = np.zeros(_grid.shape, dtype=float)
    for _idx, (_r, _c) in enumerate(_explored):
        _canvas[_r, _c] = 0.25 + 0.55 * (_idx / max(len(_explored), 1))
    _canvas[_grid] = -1.0

    _fig, _ax = plt.subplots(figsize=(8, 5))
    _cmap = plt.cm.Blues.copy()
    _cmap.set_under("#1f2937")
    _ax.imshow(_canvas, cmap=_cmap, vmin=0.0, vmax=1.0, origin="upper")

    if _path:
        _py = [_p[0] for _p in _path]
        _px = [_p[1] for _p in _path]
        _ax.plot(_px, _py, color="#16a34a", lw=3, label="Final Path")

    _ax.scatter([_start[1]], [_start[0]], s=110, color="#2563eb", ec="white", lw=1.5, zorder=5, label="Start")
    _ax.scatter([_goal[1]], [_goal[0]], s=110, color="#dc2626", ec="white", lw=1.5, zorder=5, label="Goal")
    _ax.set_xticks(np.arange(-0.5, _grid.shape[1], 1), minor=True)
    _ax.set_yticks(np.arange(-0.5, _grid.shape[0], 1), minor=True)
    _ax.grid(which="minor", color="#e5e7eb", lw=0.6)
    _ax.tick_params(which="both", bottom=False, left=False, labelbottom=False, labelleft=False)
    _ax.legend(loc="upper right", fontsize=8)
    _ax.set_title(
        f"{algo_dd.value} on '{map_dd.value}'  |  Explored: {len(_explored)} cells  |  Path length: {_plen:.2f} m"
    )

    mo.vstack([_fig])
    return


@app.cell
def _(mo):
    mo.md(r"""
    ## Try this on your own

    1. **Greedy vs. Admissible A\*:** On `"u-trap"`, compare `heuristic_weight=1.0` against `heuristic_weight=2.5`. Which explores fewer cells, and does the path length stay optimal?
    2. **Benchmark all three planners:** Run `BFS`, `Dijkstra`, and `A*` in the cell below and print a compact comparison table of `explored` vs `path_len`.
    """)
    return


@app.cell
def _(make_map, search_grid):
    # Exercise sandbox — edit and run!
    _grid_ex, _s_ex, _g_ex = make_map("u-trap")
    for _name in ("BFS", "Dijkstra", "A*"):
        _exp, _p, _len = search_grid(_grid_ex, _s_ex, _g_ex, algo=_name)
        print(f"{_name:10s} | explored = {len(_exp):3d} cells | path length = {_len:.2f} m")
    return


if __name__ == "__main__":
    app.run()
