# /// 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 1.6: End-to-End Pick and Place Loop

    Here we tie all of Course 1 together in one tabletop loop:

    1. **Detect** the block in the `camera` frame.
    2. **Transform** through the TF tree into the robot's `base` frame.
    3. **Solve IK** for the grasp joint angles.
    4. **Verify with FK** that the gripper lands within `< 1 mm` of the target.
    5. **Compare learned policy frames** when the workbench shifts!
    """)
    return


@app.cell
def _(np):
    def se2(x, y, theta_rad):
        c, s = np.cos(theta_rad), np.sin(theta_rad)
        return np.array([[c, -s, x], [s, c, y], [0.0, 0.0, 1.0]], dtype=float)

    def inv_se2(T):
        R = T[:2, :2]
        t = T[:2, 2]
        out = np.eye(3, dtype=float)
        out[:2, :2] = R.T
        out[:2, 2] = -(R.T @ t)
        return out

    def solve_grasp_ik(bx, by, l1=0.95, l2=0.85):
        r = np.clip(np.hypot(bx, by), abs(l1 - l2) + 1e-3, l1 + l2 - 1e-3)
        cos2 = np.clip((r**2 - l1**2 - l2**2) / (2 * l1 * l2), -1.0, 1.0)
        t2 = -np.arccos(cos2)
        t1 = np.arctan2(by, bx) - np.arctan2(l2 * np.sin(t2), l1 + l2 * np.cos(t2))
        return t1, t2

    def fk_grasp(t1, t2, l1=0.95, l2=0.85):
        elbow = np.array([l1 * np.cos(t1), l1 * np.sin(t1)])
        tip = elbow + np.array([l2 * np.cos(t1 + t2), l2 * np.sin(t1 + t2)])
        return elbow, tip

    return fk_grasp, inv_se2, se2, solve_grasp_ik


@app.cell
def _(mo):
    block_x = mo.ui.slider(-0.15, 0.35, step=0.02, value=0.18, label="Block X on table (m)")
    table_shift = mo.ui.slider(-0.3, 0.3, step=0.05, value=0.0, label="Shift workbench (m)")
    mo.hstack([block_x, table_shift], justify="start")
    return block_x, table_shift


@app.cell
def _(block_x, fk_grasp, inv_se2, mo, np, plt, se2, solve_grasp_ik, table_shift):
    _T_world_base = se2(-0.75, -0.35, 0.0)
    _T_world_cam = se2(0.25 + table_shift.value, 1.05, -np.pi / 2)
    _p_world_block = np.array([block_x.value + table_shift.value, -0.15, 1.0])

    # Step 1: Camera detects block in its own local frame
    _p_cam = inv_se2(_T_world_cam) @ _p_world_block

    # Step 2: TF lookup from camera -> world -> base
    _T_base_cam = inv_se2(_T_world_base) @ _T_world_cam
    _p_base = _T_base_cam @ _p_cam

    # Step 3 & 4: Solve IK in base frame and verify with FK
    _t1, _t2 = solve_grasp_ik(_p_base[0], _p_base[1])
    _elbow_b, _tip_b = fk_grasp(_t1, _t2)
    _fk_err_mm = np.hypot(_tip_b[0] - _p_base[0], _tip_b[1] - _p_base[1]) * 1000.0
    assert _fk_err_mm < 1.0

    # Transform back to world for plotting
    _base_w = _T_world_base[:2, 2]
    _elbow_w = (_T_world_base @ np.array([*_elbow_b, 1.0]))[:2]
    _tip_w = (_T_world_base @ np.array([*_tip_b, 1.0]))[:2]

    _fig, _ax = plt.subplots(figsize=(6.2, 4.0))
    _ax.plot([-1.0, 1.2], [-0.22, -0.22], lw=6, color="#cbd5e1", label="Tabletop")
    _ax.plot([_base_w[0], _elbow_w[0], _tip_w[0]], [_base_w[1], _elbow_w[1], _tip_w[1]], "-o", lw=3, color="#111827", label="Robot Arm")
    _ax.scatter([_p_world_block[0]], [_p_world_block[1]], marker="s", s=130, color="#f97316", zorder=5, label="Block")
    _ax.scatter([_T_world_cam[0, 2]], [_T_world_cam[1, 2]], marker="v", s=110, color="#2563eb", label="Camera")
    _ax.set_aspect("equal")
    _ax.set_xlim(-1.1, 1.2)
    _ax.set_ylim(-0.6, 1.3)
    _ax.grid(True, alpha=0.25)
    _ax.legend(loc="upper left", fontsize=8)
    _ax.set_title(f"FK Verify Error: {_fk_err_mm:.4f} mm  |  p_cam = ({_p_cam[0]:.2f}, {_p_cam[1]:.2f})")

    _summary = mo.md(
        f"- **Camera frame:** `({_p_cam[0]:.2f}, {_p_cam[1]:.2f}) m` *(stays constant if camera moves with table!)*\n"
        f"- **Base frame:** `({_p_base[0]:.2f}, {_p_base[1]:.2f}) m`\n"
        f"- **Solved joints:** `θ₁ = {np.rad2deg(_t1):.1f}°, θ₂ = {np.rad2deg(_t2):.1f}°`"
    )
    mo.vstack([_fig, _summary])
    return


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

    1. **Add a pre-grasp lift waypoint:** Compute IK for `(block_x, block_y + 0.25)` first so the arm approaches the block from above instead of sweeping sideways across the table.
    2. **Simulate a calibration bug:** Add a `2 cm` (`0.02 m`) error to `T_world_cam` during TF lookup and observe how far the gripper misses the block.
    """)
    return


@app.cell
def _(fk_grasp, np, solve_grasp_ik):
    # Exercise sandbox — edit and run!
    _pre_grasp_base = (0.93, 0.45)
    _grasp_base = (0.93, 0.20)
    _t_pre = solve_grasp_ik(*_pre_grasp_base)
    _t_grasp = solve_grasp_ik(*_grasp_base)
    print("Pre-grasp joints (deg):", np.round(np.rad2deg(_t_pre), 1))
    print("Grasp joints (deg):    ", np.round(np.rad2deg(_t_grasp), 1))
    print("FK check at grasp:     ", np.round(fk_grasp(*_t_grasp)[1], 4))
    return


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