"""Offline planar 2R position IK example; no robot or middleware connection.
Run: python3 numerical-example.py
Requires NumPy. Writes results.csv, verification.json and two SVG figures here.
"""
from pathlib import Path
import csv
import json
import platform
from html import escape
import numpy as np

ROOT = Path(__file__).resolve().parent
ASSETS = ROOT / 'assets'
ASSETS.mkdir(exist_ok=True)
L1 = L2 = 1.0  # m
VELOCITY = np.array([0.01, 0.0])  # base-frame m/s
DAMPING = 0.05  # m/rad, same units as J in this position-only example


def fk(q):
    a, b = q
    return np.array([L1*np.cos(a)+L2*np.cos(a+b),
                     L1*np.sin(a)+L2*np.sin(a+b)])


def jacobian(q):
    a, b = q
    return np.array([[-L1*np.sin(a)-L2*np.sin(a+b), -L2*np.sin(a+b)],
                     [L1*np.cos(a)+L2*np.cos(a+b), L2*np.cos(a+b)]])


def solve(degrees):
    q = np.deg2rad([0.0, degrees])
    J = jacobian(q)
    inverse = np.linalg.pinv(J, rcond=1e-12)
    damped = J.T @ np.linalg.solve(J @ J.T + DAMPING**2 * np.eye(2), np.eye(2))
    u = inverse @ VELOCITY
    ud = damped @ VELOCITY
    return J, inverse, damped, u, ud


rows = []
for degrees in [30.0, 5.0, 1.0, 0.1, 0.0]:
    J, inverse, damped, u, ud = solve(degrees)
    rows.append(dict(q2_deg=degrees, sigma_min_m_per_rad=np.linalg.svd(J, compute_uv=False)[-1],
                     pinv_q1_rad_s=u[0], pinv_q2_rad_s=u[1],
                     dls_q1_rad_s=ud[0], dls_q2_rad_s=ud[1],
                     pinv_residual_m_s=np.linalg.norm(J @ u - VELOCITY),
                     dls_residual_m_s=np.linalg.norm(J @ ud - VELOCITY)))
with (ROOT / 'results.csv').open('w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0]))
    writer.writeheader()
    writer.writerows(rows)

# Independent checks: finite difference FK, closed-form inverse, DLS normal
# equation, and the feasible target at the singular configuration.
q = np.deg2rad([0.0, 1.0])
J, inverse, damped, u, ud = solve(1.0)
h = 1e-6
Jfd = np.column_stack([(fk(q+h*e)-fk(q-h*e))/(2*h) for e in np.eye(2)])
fd_error = float(np.max(np.abs(J-Jfd)))
assert fd_error < 1e-8
b = q[1]
closed_form = np.array([0.01*np.cos(b)/np.sin(b), -0.01*(1+np.cos(b))/np.sin(b)])
assert np.allclose(u, closed_form, atol=1e-11)
assert np.linalg.norm(J @ u - VELOCITY) < 1e-12
assert np.allclose((J.T@J + DAMPING**2*np.eye(2))@ud, J.T@VELOCITY, atol=1e-12)
assert np.allclose(fk(np.zeros(2)), [2, 0])
assert np.linalg.matrix_rank(jacobian(np.zeros(2))) == 1
assert np.allclose(fk(np.deg2rad([0,90])), [1,1])
assert np.allclose(fk(np.deg2rad([90,-90])), [1,1])
projection_leak = float(np.linalg.norm(J @ (np.eye(2)-damped@J)))
assert projection_leak > 1e-6
verification = dict(python=platform.python_version(), numpy=np.__version__,
    length_m=[L1,L2], target_velocity_m_s=VELOCITY.tolist(), damping_m_per_rad=DAMPING,
    finite_difference_max_error=fd_error,
    damped_projector_leak_at_one_degree=projection_leak,
    checks='FK finite difference, analytical inverse, DLS optimality, singular target, two branches: passed')
(ROOT / 'verification.json').write_text(json.dumps(verification, indent=2)+'\n')

# Explicit SVG geometry keeps figures reproducible with just NumPy.
class SVG:
    def __init__(self, width, height, title):
        self.items = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img">',
                      f'<title>{escape(title)}</title>', '<rect width="100%" height="100%" fill="#ffffff"/>',
                      '<g font-family="DejaVu Sans, sans-serif" fill="#1e293b">']
    def line(self, x1, y1, x2, y2, color='#94a3b8', width=1, dash=''):
        self.items.append(f'<line x1="{x1:.3f}" y1="{y1:.3f}" x2="{x2:.3f}" y2="{y2:.3f}" stroke="{color}" stroke-width="{width}" stroke-dasharray="{dash}"/>')
    def text(self, x, y, text, size=15, anchor='start', color='#1e293b'):
        self.items.append(f'<text x="{x}" y="{y}" font-size="{size}" text-anchor="{anchor}" fill="{color}">{escape(text)}</text>')
    def circle(self,x,y,color):
        self.items.append(f'<circle cx="{x}" cy="{y}" r="6" fill="{color}"/>')
    def polyline(self, points, color):
        p = ' '.join(f'{x:.3f},{y:.3f}' for x,y in points)
        self.items.append(f'<polyline points="{p}" fill="none" stroke="{color}" stroke-width="2.5"/>')
    def save(self,name):
        (ASSETS/name).write_text('\n'.join(self.items+['</g></svg>'])+'\n')

s=SVG(880,390,'Two planar 2R IK branches for position (1, 1) m')
s.text(440,31,'Same endpoint position, two joint configurations',21,'middle')
for x0, qdeg, color, label in [(105,[0,90],'#2563eb','elbow-down'), (520,[90,-90],'#d97706','elbow-up')]:
    origin=np.array([x0,290.]); scale=155.
    def pixel(point): return origin+scale*np.array([point[0],-point[1]])
    for val in [0,1]:
        x,y=pixel([val,0]); s.text(x,y+25,str(val),13,'middle')
        x,y=pixel([0,val]); s.text(x-15,y+5,str(val),13,'end')
    s.line(*pixel([-.15,0]),*pixel([1.6,0]));s.line(*pixel([0,-.1]),*pixel([0,1.35]))
    s.text(*pixel([1.65,-.03]),'x (m)',13);s.text(*pixel([-.12,1.4]),'y (m)',13)
    a,b=np.deg2rad(qdeg)
    elbow=np.array([L1*np.cos(a),L1*np.sin(a)])
    points=[pixel([0,0]),pixel(elbow),pixel(fk([a,b]))]
    s.polyline(points,color)
    for p in points:s.circle(*p,color)
    s.text(*pixel([1.08,1.05]),'(1, 1)',14)
    s.text(x0+110,350,f'{label}: q = {qdeg} deg',15,'middle',color)
s.save('two-branches.svg')

s=SVG(960,440,'Pseudoinverse versus damped least squares near a straight 2R arm')
s.text(480,28,'2R position task: approaching full extension',21,'middle')
s.text(480,55,'L1 = L2 = 1 m; q1 = 0; desired v = (0.01, 0) m/s; damping = 0.05 m/rad',14,'middle')
angles=np.geomspace(.1,30,250)
samples=[solve(a) for a in angles]
pnorm=np.array([np.linalg.norm(t[3]) for t in samples])
dnorm=np.array([np.linalg.norm(t[4]) for t in samples])
pr=np.array([np.linalg.norm(t[0]@t[3]-VELOCITY) for t in samples])
dr=np.array([np.linalg.norm(t[0]@t[4]-VELOCITY) for t in samples])
for index,title,values,ylim,yticks,log_y in [
    (0,'Joint speed norm (rad/s)',[pnorm,dnorm],(.001,20),[.001,.01,.1,1,10],True),
    (1,'Task residual norm (m/s)',[pr,dr],(0,.0105),[0,.0025,.005,.0075,.01],False)]:
    left=80+index*470; top=110; width=365; height=240
    def px(a):return left+(np.log10(a)-np.log10(.1))/(np.log10(30)-np.log10(.1))*width
    def py(y):
        f=np.log10 if log_y else lambda a:a
        return top+height-(f(y)-f(ylim[0]))/(f(ylim[1])-f(ylim[0]))*height
    s.text(left+width/2,90,title,17,'middle')
    for tick in [.1,1,5,30]:
        x=px(tick);s.line(x,top,x,top+height,'#e2e8f0');s.text(x,top+height+22,str(tick),13,'middle')
    for tick in yticks:
        y=py(tick);s.line(left,y,left+width,y,'#e2e8f0');s.text(left-9,y+5,f'{tick:g}',12,'end')
    s.line(left,top,left,top+height);s.line(left,top+height,left+width,top+height)
    for arr,color in zip(values,['#2563eb','#d97706']):
        s.polyline([(px(a),py(v)) for a,v in zip(angles,arr)],color)
    s.text(left+width/2,397,'q2 (degrees, log scale; closer to singularity at left)',12,'middle')
s.line(280,422,310,422,'#2563eb',3);s.text(320,427,'Pseudoinverse',14)
s.line(520,422,550,422,'#d97706',3);s.text(560,427,'Damped least squares',14)
s.save('speed-residual.svg')
print(json.dumps(verification,indent=2))
for row in rows:
    print(f"q2={row['q2_deg']:5g} deg | pinv=({row['pinv_q1_rad_s']:.6f}, {row['pinv_q2_rad_s']:.6f}) | dls=({row['dls_q1_rad_s']:.6f}, {row['dls_q2_rad_s']:.6f}) | residuals=({row['pinv_residual_m_s']:.6g}, {row['dls_residual_m_s']:.6g}) m/s")
