"""
Robotic Manipulator — Standalone Python Kinematics, Workspace & Trajectory Verification
Mirrors ManipulatorApp.m, quintic_trajectory.m, cubic_vs_quintic_benchmark.m,
workspace_analyzer.m, nao_seriallink_demo.m, and puma560_ik_demo.m using NumPy.
"""

from __future__ import annotations
import math
import numpy as np


def dh_standard(theta: float, d: float, a: float, alpha: float) -> np.ndarray:
    """Standard Denavit-Hartenberg 4x4 homogeneous transformation matrix."""
    ct, st = math.cos(theta), math.sin(theta)
    ca, sa = math.cos(alpha), math.sin(alpha)
    return np.array([
        [ct, -st * ca,  st * sa, a * ct],
        [st,  ct * ca, -ct * sa, a * st],
        [0.0,      sa,       ca,      d],
        [0.0,     0.0,      0.0,    1.0],
    ], dtype=float)


def puma560_dh_table() -> list[tuple[float, float, float]]:
    """Standard Puma 560 DH parameters (d, a, alpha) in meters and radians."""
    return [
        (0.0,     0.0,     math.pi / 2),
        (0.0,     0.4318,  0.0),
        (0.15005, 0.0203, -math.pi / 2),
        (0.4318,  0.0,     math.pi / 2),
        (0.0,     0.0,    -math.pi / 2),
        (0.0,     0.0,     0.0),
    ]


def puma560_fk(q: np.ndarray) -> np.ndarray:
    """Compute 4x4 end-effector pose of the 6-DOF Puma 560."""
    T = np.eye(4)
    for theta, (d, a, alpha) in zip(q, puma560_dh_table()):
        T = T @ dh_standard(float(theta), d, a, alpha)
    return T


def puma560_numeric_jacobian(q: np.ndarray, eps: float = 1e-6) -> np.ndarray:
    """Compute 3x6 positional Jacobian by central finite differences."""
    J = np.zeros((3, 6), dtype=float)
    for i in range(6):
        dq = np.zeros(6)
        dq[i] = eps
        p_plus = puma560_fk(q + dq)[:3, 3]
        p_minus = puma560_fk(q - dq)[:3, 3]
        J[:, i] = (p_plus - p_minus) / (2.0 * eps)
    return J


def yoshikawa_manipulability(q: np.ndarray) -> float:
    """Compute Yoshikawa translational manipulability index sqrt(det(J * J^T))."""
    J = puma560_numeric_jacobian(q)
    return float(math.sqrt(max(0.0, float(np.linalg.det(J @ J.T)))))


def puma560_ik_dls(target_xyz: np.ndarray, q_init: np.ndarray | None = None,
                    max_iter: int = 300, tol: float = 1e-6) -> tuple[np.ndarray, float]:
    """Damped Least-Squares (Levenberg-Marquardt) numerical IK for 3D position."""
    q = np.zeros(6) if q_init is None else q_init.copy()
    lam = 0.05
    for _ in range(max_iter):
        pos = puma560_fk(q)[:3, 3]
        err = target_xyz - pos
        if np.linalg.norm(err) < tol:
            return q, float(np.linalg.norm(err))
        J = puma560_numeric_jacobian(q)
        dq = J.T @ np.linalg.solve(J @ J.T + (lam ** 2) * np.eye(3), err)
        q = q + dq
    final_err = float(np.linalg.norm(target_xyz - puma560_fk(q)[:3, 3]))
    return q, final_err


def solve_quintic(q0: float = 0.0, qf: float = math.pi / 2,
                  v0: float = 2e-9, vf: float = 5e-9,
                  a0_bc: float = 0.0, af_bc: float = 0.0,
                  t0: float = 3.0, tf: float = 8.0) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Solve 5th-order polynomial trajectory A*a = b."""
    A = np.array([
        [t0**5, t0**4, t0**3, t0**2, t0, 1.0],
        [5*t0**4, 4*t0**3, 3*t0**2, 2*t0, 1.0, 0.0],
        [20*t0**3, 12*t0**2, 6*t0, 2.0, 0.0, 0.0],
        [tf**5, tf**4, tf**3, tf**2, tf, 1.0],
        [5*tf**4, 4*tf**3, 3*tf**2, 2*tf, 1.0, 0.0],
        [20*tf**3, 12*tf**2, 6*tf, 2.0, 0.0, 0.0],
    ], dtype=float)
    b = np.array([q0, v0, a0_bc, qf, vf, af_bc], dtype=float)
    coeffs = np.linalg.solve(A, b)
    t = np.linspace(t0, tf, 400)
    q = np.polyval(coeffs, t)
    qd = np.polyval(np.polyder(coeffs), t)
    qdd = np.polyval(np.polyder(coeffs, 2), t)
    return coeffs, t, q, qd, qdd


def solve_cubic(q0: float = 0.0, qf: float = math.pi / 2,
                t0: float = 3.0, tf: float = 8.0) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
    """Solve 3rd-order rest-to-rest cubic polynomial trajectory."""
    A = np.array([
        [t0**3, t0**2, t0, 1.0],
        [3*t0**2, 2*t0, 1.0, 0.0],
        [tf**3, tf**2, tf, 1.0],
        [3*tf**2, 2*tf, 1.0, 0.0],
    ], dtype=float)
    b = np.array([q0, 0.0, qf, 0.0], dtype=float)
    coeffs = np.linalg.solve(A, b)
    t = np.linspace(t0, tf, 400)
    q = np.polyval(coeffs, t)
    qd = np.polyval(np.polyder(coeffs), t)
    qdd = np.polyval(np.polyder(coeffs, 2), t)
    return coeffs, t, q, qd, qdd


def nao_pr_fk(d1: float, theta2: float) -> np.ndarray:
    """2-DOF Prismatic-Revolute workshop arm (NAO_ROB) FK."""
    T1 = dh_standard(0.0, d1, 0.0, math.pi / 2)
    T2 = dh_standard(theta2, 0.0, 3.0, 0.0)
    return T1 @ T2


def check_workspace_gate(x: float, y: float, z: float) -> tuple[bool, str]:
    """Workspace gate matching ManipulatorApp.m."""
    r = math.hypot(x, y)
    theta_deg = math.degrees(math.atan2(y, x))
    if r < 0.5 or r > 1.0:
        return False, f"Radial distance r={r:.3f} m outside [0.5, 1.0] m"
    if theta_deg < -90.0 or theta_deg > 90.0:
        return False, f"Azimuth theta={theta_deg:.1f} deg outside [-90, 90] deg"
    if z < 0.0:
        return False, f"Z={z:.3f} m must be >= 0"
    return True, "Valid workspace target"


def monte_carlo_workspace(n: int = 800, seed: int = 42) -> tuple[np.ndarray, np.ndarray]:
    """Sample Puma 560 joint limits to compute reachable points and manipulability."""
    rng = np.random.default_rng(seed)
    lims = np.deg2rad([
        [-160, 160], [-110, 110], [-135, 135],
        [-266, 266], [-100, 100], [-266, 266],
    ])
    pts = np.zeros((n, 3))
    manip = np.zeros(n)
    for i in range(n):
        q = rng.uniform(lims[:, 0], lims[:, 1])
        pts[i] = puma560_fk(q)[:3, 3]
        manip[i] = yoshikawa_manipulability(q)
    return pts, manip


def run_all_checks() -> None:
    print("=== Robotic Manipulator Python Verification Suite ===")

    # 1. Quintic trajectory
    coeffs, t, q, qd, qdd = solve_quintic()
    max_bc_err = max(
        abs(q[0] - 0.0),
        abs(q[-1] - math.pi / 2),
        abs(qd[0] - 2e-9),
        abs(qd[-1] - 5e-9),
        abs(qdd[0]),
        abs(qdd[-1]),
    )
    assert max_bc_err < 1e-9, f"Quintic BC error too high: {max_bc_err}"
    print(f"[PASS] 1. Quintic trajectory: 6 coeffs solved, max BC error = {max_bc_err:.2e}")

    # 2. Cubic vs Quintic benchmark
    _, _, _, vc, ac = solve_cubic()
    assert abs(ac[0]) > 0.3 and abs(qdd[0]) < 1e-10
    print(f"[PASS] 2. Cubic vs Quintic: cubic peak |v|={np.max(np.abs(vc)):.4f} rad/s vs quintic {np.max(np.abs(qd)):.4f} rad/s (0 endpoint accel)")

    # 3. Puma 560 FK at test configuration [20, 30, -15, 10, 0, 0] deg
    q_fk = np.deg2rad([20.0, 30.0, -15.0, 10.0, 0.0, 0.0])
    T_fk = puma560_fk(q_fk)
    assert abs(np.linalg.det(T_fk[:3, :3]) - 1.0) < 1e-12
    print(f"[PASS] 3. Puma 560 FK [20,30,-15,10,0,0] deg -> XYZ = ({T_fk[0,3]:.4f}, {T_fk[1,3]:.4f}, {T_fk[2,3]:.4f}) m")

    # 4. Workspace gates
    assert check_workspace_gate(0.7, 0.2, 0.3)[0] is True
    assert check_workspace_gate(0.2, 0.1, 0.3)[0] is False
    assert check_workspace_gate(0.7, 0.2, -0.1)[0] is False
    assert check_workspace_gate(-0.7, 0.0, 0.3)[0] is False
    print("[PASS] 4. Workspace gate checks (accept (0.7,0.2,0.3), reject out-of-bounds)")

    # 5. Puma 560 DLS IK round-trip
    target = np.array([0.7, 0.2, 0.3])
    q_ik, pos_err = puma560_ik_dls(target, q_init=np.array([0.2, 0.3, -0.2, 0.0, 0.1, 0.0]))
    assert pos_err < 1e-5, f"IK error too large: {pos_err}"
    print(f"[PASS] 5. Puma 560 IK->FK round-trip for (0.7, 0.2, 0.3): error = {pos_err:.2e} m")

    # 6. Yoshikawa manipulability & Monte Carlo workspace
    w_ik = yoshikawa_manipulability(q_ik)
    pts, manip = monte_carlo_workspace(400)
    assert w_ik > 0.01 and float(np.max(manip)) > 0.05
    print(f"[PASS] 6. Manipulability w(q_ik) = {w_ik:.4f}, MC max reach = {np.max(np.hypot(pts[:,0], pts[:,1])):.3f} m")

    # 7. NAO_ROB 2-DOF PR arm
    T_nao = nao_pr_fk(4.0, 0.3)
    assert abs(T_nao[2, 3] - (4.0 + 3.0 * math.sin(0.3))) < 1e-12
    print(f"[PASS] 7. NAO_ROB PR arm FK([4.0, 0.3]) -> XYZ = ({T_nao[0,3]:.4f}, {T_nao[1,3]:.4f}, {T_nao[2,3]:.4f}) m")

    print("=== All 7 verification checks passed ===")


if __name__ == "__main__":
    run_all_checks()
