"""FR3 (fairino3_v6.urdf) on MITRA front edge: tipping check.
Arm link masses / CoM / joint offsets are read from the official URDF.
MITRA values not published (wheelbase, CG, controller mass) are assumptions, varied below.
"""
import sys, math, itertools
import numpy as np
import xml.etree.ElementTree as ET

URDF = sys.argv[1]
root = ET.parse(URDF).getroot()

def rpy_mat(r, p, y):
    cr, sr, cp, sp, cy, sy = math.cos(r), math.sin(r), math.cos(p), math.sin(p), math.cos(y), math.sin(y)
    return np.array([[cy*cp, cy*sp*sr - sy*cr, cy*sp*cr + sy*sr],
                     [sy*cp, sy*sp*sr + cy*cr, sy*sp*cr - cy*sr],
                     [-sp, cp*sr, cp*cr]])

def T(xyz, rpy):
    M = np.eye(4); M[:3, :3] = rpy_mat(*rpy); M[:3, 3] = xyz; return M

def rotz(a):
    M = np.eye(4); M[:2, :2] = [[math.cos(a), -math.sin(a)], [math.sin(a), math.cos(a)]]; return M

f = lambda s: [float(v) for v in s.split()]
links = {}
for l in root.findall('link'):
    m = l.find('inertial/mass')
    if m is None: continue
    o = l.find('inertial/origin')
    links[l.get('name')] = (float(m.get('value')), np.array(f(o.get('xyz')) + [1.0]))
joints = [j for j in root.findall('joint') if j.get('type') == 'revolute']

def com_points(q, payload_kg, tool_len):
    """world (arm-base frame) mass points for joint angles q"""
    pts = []
    M = np.eye(4)
    first_parent = joints[0].find('parent').get('link')
    m0, c0 = links[first_parent]
    pts.append((m0, (M @ c0)[:3]))
    for j, a in zip(joints, q):
        o = j.find('origin')
        M = M @ T(f(o.get('xyz')), f(o.get('rpy'))) @ rotz(a)
        child = j.find('child').get('link')
        if child in links:
            m, c = links[child]
            pts.append((m, (M @ c)[:3]))
    # payload (gripper + object) at tool_len along flange z
    pts.append((payload_kg, (M @ np.array([0, 0, tool_len, 1.0]))[:3]))
    return pts

arm_mass = sum(m for m, _ in links.values())
print(f"URDF arm mass: {arm_mass:.2f} kg")

# worst forward reach of the mass: search joint 2,3,4 (j1 = 0 so arm points along base x)
best = None
rng = np.radians
for q2, q3, q4 in itertools.product(np.arange(-180, 1, 5), np.arange(-160, 161, 5), np.arange(-180, 1, 15)):
    q = [0, rng(q2), rng(q3), rng(q4), rng(90), 0]
    pts = com_points(q, 3.0, 0.15)
    # flange / payload must stay above the deck (z >= -0.03 relative to arm base) -> realistic poses
    if min(p[2] for _, p in pts) < -0.03: continue
    mx = sum(m * p[0] for m, p in pts); mtot = sum(m for m, _ in pts)
    h = sum(m * p[2] for m, p in pts) / mtot
    r = abs(mx)
    if best is None or r > best[0]:
        best = (r, mtot, h, q, pts)
r, mtot, h, q, pts = best
print(f"worst pose deg: {[round(math.degrees(a)) for a in q]}")
print(f"arm+payload mass {mtot:.2f} kg, mass moment about arm base axis {r:.2f} kg*m "
      f"(CoM {r/mtot*1000:.0f} mm out), CoM height above arm base {h*1000:.0f} mm")
reach_pt = max(abs(p[0]) for _, p in pts)
print(f"payload point reach {reach_pt*1000:.0f} mm")

# --- MITRA side (x forward, 0 = deck front edge). Assumptions:
DECK_H = 0.355; DECK_LEN = 0.887
ARM_X = -0.065                     # arm base centre, 65 mm behind deck front
MITRA_M = 85.0; MITRA_CGZ = 0.20   # CG height assumed
CTRL_M = 10.0; CTRL_X = -DECK_LEN + 0.135; CTRL_Z = DECK_H + 0.10   # control+safety box, assumed
TRAY_M = 5.0; TRAY_X = -0.45; TRAY_Z = DECK_H + 0.07
TRACK = 0.505                      # wheel centre-to-centre (590 outer - 85 tyre)

def margin(axle_front_x, wheelbase, mitra_cg_x, slope_deg, decel_g, lateral):
    th = math.radians(slope_deg)
    masses = [(MITRA_M, mitra_cg_x, 0, MITRA_CGZ),
              (CTRL_M, CTRL_X, 0, CTRL_Z),
              (TRAY_M, TRAY_X, 0, TRAY_Z)]
    zb = DECK_H
    if not lateral:
        masses.append((mtot, ARM_X + r / mtot, 0, zb + h))
        # tipping line: front tyre contact. Facing downhill: gravity tilts forward by slope.
        # effective horizontal arm of each mass = (x - xa)*cos + z*sin(slope) ; braking adds z*decel
        tip = sum(m * ((x - axle_front_x) * math.cos(th) + z * math.sin(th) + z * decel_g) for m, x, _, z in masses)
        resist = -sum(m * min(0, ((x - axle_front_x) * math.cos(th) + z * math.sin(th) + z * decel_g)) for m, x, _, z in masses)
        over = sum(m * max(0, ((x - axle_front_x) * math.cos(th) + z * math.sin(th) + z * decel_g)) for m, x, _, z in masses)
    else:
        masses.append((mtot, ARM_X, r / mtot, zb + h))
        yl = TRACK / 2
        resist = -sum(m * min(0, (y - yl) * math.cos(th) + z * math.sin(th)) for m, _, y, z in masses)
        over = sum(m * max(0, (y - yl) * math.cos(th) + z * math.sin(th)) for m, _, y, z in masses)
    return resist / over if over > 0 else float('inf')

print("\n安全率 = 倒れを止める力のモーメント / 倒そうとするモーメント（1 未満で倒れる）")
for wb in (0.50, 0.60, 0.70):
    for axle_off in (0.15, 0.25):
        afx = -axle_off
        cgx = afx - wb / 2
        row = []
        for slope, dec in ((0, 0), (10, 0), (0, 0.3)):
            row.append(margin(afx, wb, cgx, slope, dec, False))
        lat = [margin(afx, wb, cgx, s, 0, True) for s in (0, 10)]
        print(f"wheelbase {wb*1000:.0f} / front axle {axle_off*1000:.0f}mm behind edge: "
              f"前 平地 {row[0]:.1f}, 前 10°下り {row[1]:.1f}, 前 急停止0.3g {row[2]:.1f} | "
              f"横 平地 {lat[0]:.1f}, 横 10°傾き {lat[1]:.1f}")
