% VERIFY_KINEMATICS Automated verification suite for trajectory & kinematics modules.
% Run in MATLAB: cd('REPO_ROOT'); addpath(genpath('src')); run('tests/verify_kinematics.m')

fprintf('=== Running Robotic Manipulator MATLAB Verification Suite ===\n');
passed = 0; failed = 0;

%% Test 1: Quintic Trajectory Boundary Conditions
[coeffs, t, q, qd, qdd] = quintic_trajectory(0, pi/2, 2e-9, 5e-9, 0, 0, 3, 8, false);
err_q0 = abs(q(1) - 0);
err_qf = abs(q(end) - pi/2);
err_v0 = abs(qd(1) - 2e-9);
err_vf = abs(qd(end) - 5e-9);
err_a0 = abs(qdd(1));
err_af = abs(qdd(end));
max_err = max([err_q0, err_qf, err_v0, err_vf, err_a0, err_af]);
if max_err < 1e-8 && numel(coeffs) == 6 && numel(t) == 400
    fprintf('[PASS] Test 1: Quintic boundary conditions (max error = %.2e)\n', max_err);
    passed = passed + 1;
else
    fprintf('[FAIL] Test 1: Quintic boundary error too large (%.2e)\n', max_err);
    failed = failed + 1;
end

%% Test 2: Planar 2-Link + Z Forward Kinematics Consistency
th = deg2rad([30, 45, 10, 0]);
x_exp = cos(th(1)) + cos(th(1) + th(2));
y_exp = sin(th(1)) + sin(th(1) + th(2));
z_exp = th(3);
T_planar = [1 0 0 x_exp; 0 1 0 y_exp; 0 0 1 z_exp; 0 0 0 1];
if abs(det(T_planar(1:3,1:3)) - 1) < 1e-12 && abs(T_planar(4,4) - 1) < 1e-12
    fprintf('[PASS] Test 2: Planar 4x4 homogeneous pose (X=%.4f, Y=%.4f, Z=%.4f)\n', x_exp, y_exp, z_exp);
    passed = passed + 1;
else
    fprintf('[FAIL] Test 2: Invalid homogeneous transform\n');
    failed = failed + 1;
end

%% Test 3: Workspace Gate Validation
inWorkspace = @(x,y,z) (hypot(x,y) >= 0.5 && hypot(x,y) <= 1.0 && atan2d(y,x) >= -90 && atan2d(y,x) <= 90 && z >= 0);
if inWorkspace(0.7, 0.2, 0.3) && ~inWorkspace(0.2, 0.1, 0.3) && ~inWorkspace(0.7, 0.2, -0.1) && ~inWorkspace(-0.7, 0.0, 0.3)
    fprintf('[PASS] Test 3: IK workspace radial/angular/Z gates\n');
    passed = passed + 1;
else
    fprintf('[FAIL] Test 3: Workspace gate mismatch\n');
    failed = failed + 1;
end

%% Test 4: Puma 560 FK/IK Round-Trip (Robotics System Toolbox)
if exist('loadrobot', 'file') == 2
    p560 = loadrobot('puma560', 'DataFormat', 'row', 'Gravity', [0 0 -9.81]);
    ik = inverseKinematics('RigidBodyTree', p560);
    target = trvec2tform([0.7, 0.2, 0.3]);
    [q_sol, info] = ik('link6', target, [0 0 0 1 1 1], zeros(1, 6));
    T_fk = getTransform(p560, q_sol, 'link6');
    pos_err = norm(T_fk(1:3,4) - [0.7; 0.2; 0.3]);
    if pos_err < 1e-3
        fprintf('[PASS] Test 4: Puma 560 IK->FK round-trip (pos error = %.2e m, status = %s)\n', pos_err, info.Status);
        passed = passed + 1;
    else
        fprintf('[FAIL] Test 4: Puma 560 IK->FK error = %.4f m\n', pos_err);
        failed = failed + 1;
    end
else
    fprintf('[SKIP] Test 4: Robotics System Toolbox not available\n');
end

fprintf('=== Summary: %d passed, %d failed ===\n', passed, failed);
if failed > 0
    error('Verification suite failed.');
end
