# /// 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 marimo as mo
    import matplotlib.pyplot as plt
    import numpy as np

    return mo, np, plt


@app.cell
def _(mo):
    mo.md(r"""
    # Module 3.1: Configuration Space (C-Space) Intuition

    In physical **workspace**, a 2-link arm has extended limbs sweeping around obstacles. In **configuration space**, the entire arm collapses to a single point $(\theta_1, \theta_2)$, while physical obstacles warp into curved forbidden regions.
    """)
    return


@app.cell
def _(np):
    def fk_2link(t1_deg, t2_deg, l1=0.95, l2=0.75):
        """Return base, elbow, and tip (x, y) coordinates for a 2-link planar arm."""
        r1 = np.deg2rad(t1_deg)
        r12 = np.deg2rad(t1_deg + t2_deg)
        base = np.array([0.0, 0.0])
        elbow = np.array([l1 * np.cos(r1), l1 * np.sin(r1)])
        tip = elbow + np.array([l2 * np.cos(r12), l2 * np.sin(r12)])
        return base, elbow, tip

    def point_to_segment_dist(p, a, b):
        """Shortest Euclidean distance from point p to segment [a, b]."""
        ab = b - a
        denom = float(np.dot(ab, ab))
        if denom < 1e-12:
            return float(np.linalg.norm(p - a))
        t = np.clip(float(np.dot(p - a, ab)) / denom, 0.0, 1.0)
        proj = a + t * ab
        return float(np.linalg.norm(p - proj))

    def check_arm_collision(t1_deg, t2_deg, obs_xy, obs_r, l1=0.95, l2=0.75):
        """Return (link1_hit, link2_hit) against a circular workspace obstacle."""
        base, elbow, tip = fk_2link(t1_deg, t2_deg, l1, l2)
        obs = np.asarray(obs_xy, dtype=float)
        hit1 = point_to_segment_dist(obs, base, elbow) <= obs_r + 0.04
        hit2 = point_to_segment_dist(obs, elbow, tip) <= obs_r + 0.04
        return hit1, hit2

    def compute_cspace_map(obs_xy, obs_r, n_bins=48):
        """Sample a n_bins x n_bins (theta1, theta2) collision grid (0=free, 1=L2, 2=L1)."""
        angles = np.linspace(-180.0, 180.0, n_bins, endpoint=False) + (180.0 / n_bins)
        grid = np.zeros((n_bins, n_bins), dtype=int)
        for row_idx, t2 in enumerate(angles):
            for col_idx, t1 in enumerate(angles):
                h1, h2 = check_arm_collision(t1, t2, obs_xy, obs_r)
                if h1:
                    grid[row_idx, col_idx] = 2
                elif h2:
                    grid[row_idx, col_idx] = 1
        return angles, grid

    return check_arm_collision, compute_cspace_map, fk_2link


@app.cell
def _(mo):
    t1_s = mo.ui.slider(-180, 180, step=5, value=35, label="θ₁ (deg)")
    t2_s = mo.ui.slider(-180, 180, step=5, value=-60, label="θ₂ (deg)")
    obs_x_s = mo.ui.slider(-1.5, 1.5, step=0.05, value=0.85, label="Obstacle X (m)")
    obs_y_s = mo.ui.slider(-1.5, 1.5, step=0.05, value=0.65, label="Obstacle Y (m)")
    obs_r_s = mo.ui.slider(0.12, 0.55, step=0.02, value=0.30, label="Obstacle R (m)")

    mo.vstack([
        mo.hstack([t1_s, t2_s], justify="start"),
        mo.hstack([obs_x_s, obs_y_s, obs_r_s], justify="start"),
    ])
    return obs_r_s, obs_x_s, obs_y_s, t1_s, t2_s


@app.cell
def _(
    check_arm_collision,
    compute_cspace_map,
    fk_2link,
    mo,
    np,
    obs_r_s,
    obs_x_s,
    obs_y_s,
    plt,
    t1_s,
    t2_s,
):
    _obs = (obs_x_s.value, obs_y_s.value)
    _obs_r = obs_r_s.value
    _t1, _t2 = t1_s.value, t2_s.value

    _base, _elbow, _tip = fk_2link(_t1, _t2)
    _h1, _h2 = check_arm_collision(_t1, _t2, _obs, _obs_r)
    _angles, _grid = compute_cspace_map(_obs, _obs_r, n_bins=48)
    _pct_blocked = 100.0 * float(np.mean(_grid > 0))

    _fig, (_ax1, _ax2) = plt.subplots(1, 2, figsize=(10, 4.4))

    # Left: Workspace
    _ax1.add_patch(plt.Circle((0, 0), 1.70, fill=False, ls="--", color="#9ca3af", alpha=0.6))
    _ax1.add_patch(plt.Circle(_obs, _obs_r, color="#dc2626", alpha=0.25, ec="#dc2626", lw=2))
    _ax1.plot(
        [_base[0], _elbow[0]],
        [_base[1], _elbow[1]],
        "-o",
        lw=4,
        color="#dc2626" if _h1 else "#111827",
        label="Link 1",
    )
    _ax1.plot(
        [_elbow[0], _tip[0]],
        [_elbow[1], _tip[1]],
        "-o",
        lw=3.5,
        color="#dc2626" if _h2 else "#2563eb",
        label="Link 2",
    )
    _ax1.set_aspect("equal")
    _ax1.set_xlim(-1.85, 1.85)
    _ax1.set_ylim(-1.85, 1.85)
    _ax1.grid(True, alpha=0.25)
    _ax1.set_title("Collision!" if (_h1 or _h2) else "Workspace: Collision-Free")
    _ax1.legend(loc="upper left", fontsize=8)

    # Right: C-Space
    _ax2.imshow(
        _grid,
        origin="lower",
        extent=[-180, 180, -180, 180],
        cmap="Reds",
        vmin=0,
        vmax=2.2,
        aspect="equal",
    )
    _ax2.scatter([_t1], [_t2], s=70, color="#2563eb", ec="white", lw=1.5, zorder=5)
    _ax2.set_xlabel("θ₁ (deg)")
    _ax2.set_ylabel("θ₂ (deg)")
    _ax2.set_title(f"C-Space (θ₁, θ₂) — {_pct_blocked:.1f}% Blocked")
    _ax2.grid(True, alpha=0.2)

    mo.vstack([_fig])
    return


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

    1. **Vertical stripes vs. diagonal bands:** Place the obstacle at `(0.55, 0.0)` with `obs_r = 0.25` and compare the C-space shape to placing it at `(1.35, 0.0)`. Why does the close obstacle carve out a full vertical column?
    2. **Check a straight-line joint path:** Linearly interpolate 30 steps between `(-90°, 40°)` and `(90°, -40°)` around obstacle `(0.85, 0.65, 0.30)`. Print how many steps collide!
    """)
    return


@app.cell
def _(check_arm_collision, np):
    # Exercise sandbox — edit and run!
    _q_start = np.array([-90.0, 40.0])
    _q_goal = np.array([90.0, -40.0])
    _hits = 0
    for _alpha in np.linspace(0.0, 1.0, 30):
        _q = (1.0 - _alpha) * _q_start + _alpha * _q_goal
        _h1, _h2 = check_arm_collision(_q[0], _q[1], (0.85, 0.65), 0.30)
        if _h1 or _h2:
            _hits += 1
    print(f"Linear C-space interpolation collisions: {_hits} / 30 samples")
    return


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