"""Reproduce the three figures for the teaching/replay case study.

Install with: python -m pip install numpy matplotlib
Run with: python teach_replay_lab.py --out .
From the website root, set --out public/images/learning/robot-arm-development
All records are synthetic. This script never connects to a robot.
"""

import argparse
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np


L1 = L2 = 0.30                    # m
A = np.array([0.42, 0.12])       # base-frame tool positions, m
B = np.array([0.24, 0.36])
CHORD = B - A
NORMAL = np.array([CHORD[1], -CHORD[0]]) / np.linalg.norm(CHORD)
DT = 0.01                        # s, shared sample interval
DWELL = 2.0                      # s, intentional task event at B
TAU = 0.08                       # s, illustrative joint tracking lag
U_GRID = np.linspace(0, 1, 501)
TEAL, ORANGE, BLUE, INK = "#08796e", "#a84716", "#27559a", "#172f42"


def time_grid(duration):
    return np.arange(round(duration / DT) + 1) * DT


def quintic(u):
    """Zero endpoint velocity and acceleration, normalized position progress."""
    u = np.clip(u, 0.0, 1.0)
    return u ** 3 * (10.0 + u * (-15.0 + 6.0 * u))


def progress(t, duration, hesitation=None):
    if hesitation is None:
        return quintic(t / duration)
    start, end = hesitation
    fraction = 0.42              # distance fraction from this leg's start
    return np.where(t < start, fraction * quintic(t / start),
                    fraction + (1 - fraction) * quintic((t - end) / (duration - end)))


def station_clock(t, outbound, inbound, out_pause=None, in_pause=None):
    """The clock follows the annotated events. No automatic segmentation."""
    outbound_u = progress(t, outbound, out_pause)
    inbound_u = 1.0 - progress(t - outbound - DWELL, inbound, in_pause)
    return np.where(t <= outbound, outbound_u,
                    np.where(t < outbound + DWELL, 1.0, inbound_u))


def curve(u, bulge, ripple=0.0):
    """Chord projection is u because the entire offset is perpendicular to it."""
    u = np.asarray(u)
    offset = 4.0 * bulge * u * (1.0 - u) + ripple * np.sin(2*np.pi*u) * np.sin(np.pi*u)
    return A + u[..., None] * CHORD + offset[..., None] * NORMAL


def ik(xy):
    """Analytic planar 2R IK, fixed positive-q2 branch, in radians."""
    x, y = xy.T
    c2 = (x*x + y*y - L1*L1 - L2*L2) / (2.0*L1*L2)
    if np.any(np.abs(c2) > 1.0 + 1e-12):
        raise ValueError("unreachable point")
    q2 = np.arccos(np.clip(c2, -1.0, 1.0))
    q1 = np.arctan2(y, x) - np.arctan2(L2*np.sin(q2), L1 + L2*np.cos(q2))
    return np.column_stack((q1, q2))


def fk(q):
    q1, q2 = q.T
    return np.column_stack((L1*np.cos(q1) + L2*np.cos(q1+q2),
                            L1*np.sin(q1) + L2*np.sin(q1+q2)))


def station(xy):
    return (xy - A) @ CHORD / (CHORD @ CHORD)


def make_demo(outbound, inbound, out_pause, in_pause, bulge, ripple):
    t = time_grid(outbound + DWELL + inbound)
    u = station_clock(t, outbound, inbound, out_pause, in_pause)
    q = ik(curve(u, bulge, ripple))
    return dict(t=t, q=q, xy=fk(q), out=outbound, back=inbound)


def phase_profiles(demo):
    """Compare in space within each phase, giving each leg equal weight."""
    t, xy = demo["t"], demo["xy"]
    # Journeys are paired A→B with A→B and B→A with B→A first.
    # Reverse inward samples only to express each geometric profile on A→B axes.
    legs = (xy[t <= demo["out"]], xy[t >= demo["out"] + DWELL][::-1])
    result = []
    for leg in legs:
        u = station(leg)
        if np.any(np.diff(u) < -1e-10):
            raise ValueError("the chosen chord projection is not monotone on this leg")
        u, unique = np.unique(u, return_index=True)    # remove plateau repeats
        offset = (leg[unique] - A) @ NORMAL
        result.append(np.interp(U_GRID, u, offset))
    return np.array(result)                          # out, back


def fit_path(profiles):
    # Fit b in P(u) = A + u(B-A) + 4b*u*(1-u)*n. Event dwell is excluded.
    basis = 4.0 * U_GRID * (1.0 - U_GRID)
    average = profiles.mean(axis=(0, 1))
    return float(average @ basis / (basis @ basis))


def track(outbound, inbound, bulge):
    t = time_grid(outbound + DWELL + inbound)
    u = station_clock(t, outbound, inbound)
    ref_xy = curve(u, bulge)
    requested = ik(ref_xy)
    accepted = requested.copy()   # ideal acceptance, no Core governor simulated
    measured = np.empty_like(accepted)
    measured[0] = accepted[0]
    decay = np.exp(-DT / TAU)
    for k in range(1, len(t)):
        # Exact first-order response to the previous sample held for one interval.
        measured[k] = decay*measured[k-1] + (1.0-decay)*accepted[k-1]
    measured_xy = fk(measured)
    time_error = np.linalg.norm(measured_xy - ref_xy, axis=1)
    # Same-station geometry residual, not a nearest-point distance. Since the
    # out/back path is shared, this residual does not establish task timing.
    measured_u = np.clip(station(measured_xy), 0.0, 1.0)
    geometry_error = np.linalg.norm(measured_xy - curve(measured_u, bulge), axis=1)
    return dict(t=t, u=u, q=requested, measured_u=measured_u, err=time_error,
                geom_err=geometry_error, xy=ref_xy)


def rms(x):
    return np.sqrt(np.mean(np.square(x)))


def style():
    plt.rcParams.update({
        "font.family": "DejaVu Sans", "font.size": 11,
        "axes.spines.top": False, "axes.spines.right": False,
        "axes.edgecolor": "#647887", "axes.labelcolor": INK, "text.color": INK,
        "xtick.color": INK, "ytick.color": INK, "axes.axisbelow": True,
        "grid.color": "#e0e7e9", "grid.linewidth": 0.75, "lines.linewidth": 2.1,
        "legend.frameon": False, "savefig.facecolor": "white",
        "axes.facecolor": "white", "svg.fonttype": "path",
        "svg.hashsalt": "serialarm-teach-replay-v1",
    })


def save(fig, directory, suffix):
    path = directory / f"teach-replay-{suffix}.svg"
    fig.savefig(path, metadata={"Date": None}, bbox_inches="tight", pad_inches=0.15)
    plt.close(fig)
    # Matplotlib leaves a space at the end of each line of path coordinates.
    lines = path.read_bytes().splitlines()
    path.write_bytes(b"\n".join(line.rstrip() for line in lines) + b"\n")


def plot_events(demos, directory):
    fig, axes = plt.subplots(2, 1, sharex=True, figsize=(8, 4.2), layout="constrained")
    for ax, d, color, label, pause in zip(
            axes, demos, (TEAL, ORANGE), ("Demonstration 1", "Demonstration 2"),
            ((1.35, 1.85), (6.50, 7.20))):
        ax.axvspan(d["out"], d["out"]+DWELL, color="#d6e9dc", alpha=.85)
        ax.axvspan(*pause, color="#f8dfb9", alpha=.95)
        ax.plot(d["t"], station(d["xy"]), color=color)
        ax.text(.01, .92, label, transform=ax.transAxes, va="top", weight="bold")
        ax.text(d["out"]+1, .57, "2 s at B", ha="center", fontsize=10)
        ax.annotate("hesitation", (sum(pause)/2, .42 if d is demos[0] else .58),
                    xytext=(0, -23), textcoords="offset points", ha="center", fontsize=9)
        ax.set_yticks([0, .5, 1], ["A", "0.5", "B"])
        ax.set_ylim(-.09, 1.12)
        ax.grid(axis="x")
    axes[-1].set_xlabel("Time (s)")
    fig.supylabel("Chord station, u")
    save(fig, directory, "events")


def plot_path(demos, profiles, fit, directory):
    fig, (left, right) = plt.subplots(1, 2, figsize=(9, 4), layout="constrained")
    for i, (d, color) in enumerate(zip(demos, (TEAL, ORANGE)), start=1):
        span = d["t"] <= d["out"]
        left.plot(*d["xy"][span].T * 1000, color=color, label=f"Demo {i}")
        right.plot(U_GRID, profiles[i-1, 0]*1000, color=color)
    xy = curve(U_GRID, fit) * 1000
    left.plot(*xy.T, "--", color=INK, label="Fitted path")
    left.plot(*np.vstack((A, B)).T * 1000, ":", color="#71818c", label="A-B chord")
    right.plot(U_GRID, 4.0 * fit * U_GRID * (1.0-U_GRID) * 1000, "--", color=INK)
    for label, u, offset in (("A", 0.0, (6, -4)), ("M", .5, (6, 3)), ("B", 1.0, (6, 0))):
        p = curve(u, fit) * 1000
        left.plot(*p, "o", color=INK, ms=4)
        left.annotate(label, p, xytext=offset, textcoords="offset points", weight="bold")
    left.set_aspect("equal", adjustable="box")
    left.set(xlabel="TCP x (mm)", ylabel="TCP y (mm)", xlim=(210, 456), ylim=(107, 379))
    left.legend(loc="lower left", fontsize=8)
    right.set(xlabel="Chord station, u", ylabel="Offset from chord (mm)",
              xlim=(-.015, 1.015), ylim=(-2, 60))
    for ax in (left, right):
        ax.grid()
    save(fig, directory, "path")


def plot_tracking(runs, directory):
    fig, (upper, lower) = plt.subplots(2, 1, sharex=True, figsize=(8, 5), layout="constrained")
    for run, color, label in zip(runs, (TEAL, BLUE), ("4 s leg", "2 s leg")):
        upper.plot(run["t"], run["u"], color=color, label=f"{label}, reference")
        upper.plot(run["t"], run["measured_u"], "--", color=color, linewidth=1.5,
                   label=f"{label}, feedback")
        lower.plot(run["t"], run["err"] * 1000, color=color, label=label)
    upper.legend(ncol=2, loc="upper right", bbox_to_anchor=(1, -.03), fontsize=8.5)
    upper.set(ylabel="Chord station, u", ylim=(-.07, 1.09))
    lower.set(xlabel="Time (s)", ylabel="TCP error (mm)", ylim=(0, None))
    lower.legend(loc="upper right", fontsize=9)
    for ax in (upper, lower):
        ax.grid()
    save(fig, directory, "tracking")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--out", type=Path, default=Path("."), help="figure directory")
    args = parser.parse_args()
    args.out.mkdir(parents=True, exist_ok=True)
    demos = [make_demo(4.0, 3.0, (1.35, 1.85), None, .054, .003),
             make_demo(3.0, 4.5, None, (1.50, 2.20), .046, -.003)]
    profiles = np.asarray([phase_profiles(d) for d in demos])
    fit = fit_path(profiles)
    offsets = 4.0 * fit * U_GRID * (1.0 - U_GRID)
    runs = [track(4.0, 4.0, fit), track(2.0, 2.0, fit)]
    print("Synthetic inputs. Lengths in m, time in s, angles in rad.")
    print(f"Fitted bulge = {fit:.7f} m; M = {curve(.5, fit)} m")
    for i, (d, residual) in enumerate(zip(demos, profiles - offsets), start=1):
        print(f"Demo {i}: {len(d['t'])} samples; geometry RMS/max "
              f"{rms(residual)*1000:.3f}/{np.abs(residual).max()*1000:.3f} mm")
    print(f"Paired demo RMS difference: out = {rms(profiles[0,0]-profiles[1,0])*1000:.3f} mm,"
          f" back = {rms(profiles[0,1]-profiles[1,1])*1000:.3f} mm")
    print(f"Max chord shortcut error relative to fitted path = {max(offsets)*1000:.3f} mm")
    for run in runs:
        peak = np.linalg.norm(np.diff(run["xy"], axis=0), axis=1).max() / DT
        print(f"{run['t'][-1]:.0f} s cycle: peak ref speed = {peak:.5f} m/s; "
              f"time-paired TCP RMS/max = {rms(run['err'])*1000:.3f}/{run['err'].max()*1000:.3f} mm; "
              f"same-station geometry RMS = {rms(run['geom_err'])*1000:.3f} mm")
    style()
    plot_events(demos, args.out)
    plot_path(demos, profiles, fit, args.out)
    plot_tracking(runs, args.out)


if __name__ == "__main__":
    main()
