"""FR3 を MITRA の前の端に載せたときの倒れにくさ（LOG642 の tip_calc_585.py を元に、FR3 のカタログの値で前提を入れ替えた版）。

LOG642 から変えたこと:
  - アームの重さ：URDF の合計 13.73kg を、カタログの約15kg に合わせる。足りない 1.27kg の置き方を2通り試す
      base   … 付け根にまとめて置く（付け根の重さがモデルに入っていないとみなす）
      scale  … 各部の重さを同じ割合で増やす（腕の先ほど重くなるので、倒れる側に厳しい）
  - 制御箱：仮の 10kg（270×300×200mm）から、カタログの直流の小さい制御箱 2.044kg（245×180×44.5mm）に替える
  - 腕の上の重さを増やした場合と、荷台の後ろの重さを減らした場合を、別々にも見る
使い方:
    python3 tip_calc_fr3spec.py <fairino3_v6.urdf のパス>
以下は元のスクリプトの説明。
FR3 (fairino3_v6.urdf) on MITRA front edge: tipping check (LOG642: wheelbase and axle position from the press drawing).
Arm link masses / CoM / joint offsets are read from the official URDF.
Wheelbase 585 mm is written in the drawing; the front axle is 125.5 mm behind the deck front edge (measured on the drawing).
Still assumed: MITRA CG (varied below), controller mass, tray mass.
"""
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

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

def set_mass(mode):
    global links
    links = dict(LINKS_URDF)
    if mode == 'base':
        m, c = links['base_link']
        links['base_link'] = (m + CATALOG_MASS - arm_mass, c)
    elif mode == 'scale':
        k = CATALOG_MASS / arm_mass
        links = {n: (m * k, c) for n, (m, c) in LINKS_URDF.items()}

def worst_pose():

    # 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")
    return r, mtot, h, q

# --- MITRA side (x forward, 0 = deck front edge)
DECK_H = 0.355                     # arm mounting surface height (replaced below)
DECK_LEN = 0.887
ARM_X = -0.065                     # arm base centre, 65 mm behind deck front
MITRA_M = 85.0                     # written
WHEELBASE = 0.585                  # written in the drawing
AXLE_FRONT_X = -0.1255             # measured on the drawing
CTRL_M = 10.0; CTRL_X = -DECK_LEN + 0.135    # control+safety box, assumed
TRAY_M = 5.0; TRAY_X = -0.45
TRACK = 0.505                      # wheel centre-to-centre (590 outer - 85 tyre)

def margin(axle_front_x, mitra_cg_x, mitra_cg_z, slope_deg, decel_g, lateral):
    th = math.radians(slope_deg)
    masses = [(MITRA_M, mitra_cg_x, 0, mitra_cg_z),
              (CTRL_M, CTRL_X, 0, DECK_H + 0.10),
              (TRAY_M, TRAY_X, 0, DECK_H + 0.07)]
    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')

RESULT = {}
def run(label, mass_mode, ctrl_m):
    global r, mtot, h, CTRL_M, DECK_H
    set_mass(mass_mode)
    r, mtot, h, q = worst_pose()
    CTRL_M = ctrl_m
    print(f"\n=== {label}（アーム {sum(m for m,_ in links.values()):.2f}kg・置き方 {mass_mode}・制御箱 {ctrl_m}kg） ===")
    print(f"一番悪い姿勢 {[round(math.degrees(a)) for a in q]}、腕と荷物 {mtot:.2f}kg、重心は付け根から {r/mtot*1000:.0f}mm 先・高さ {h*1000:.0f}mm")
    mid = AXLE_FRONT_X - WHEELBASE / 2
    for deck_h, name in ((0.355, "丸パイプの枠の上 355mm"), (0.398, "アルミフレームの上 398mm")):
        DECK_H = deck_h
        print(f"載せる面 = {name}")
        for cg_dx, cg_z in ((0.0, 0.20), (0.05, 0.20), (-0.05, 0.20), (0.0, 0.25)):
            cgx = mid + cg_dx
            row = [margin(AXLE_FRONT_X, cgx, cg_z, slope, dec, False) for slope, dec in ((0, 0), (10, 0), (0, 0.3))]
            lat = [margin(AXLE_FRONT_X, cgx, cg_z, sl, 0, True) for sl in (0, 10)]
            print(f"  台車の重心 車軸の中間から{cg_dx*1000:+.0f}mm・高さ{cg_z*1000:.0f}mm: "
                  f"前 平地 {row[0]:.1f}, 前 10°下り {row[1]:.1f}, 前 急停止0.3g {row[2]:.1f} | "
                  f"横 平地 {lat[0]:.1f}, 横 10°傾き {lat[1]:.1f}")

print("\n安全率 = 倒れを止める力のモーメント / 倒そうとするモーメント（1 未満で倒れる）")
print(f"ホイールベース {WHEELBASE*1000:.0f}mm、前の車軸は荷台の前の端から {-AXLE_FRONT_X*1000:.1f}mm 後ろ")
run("LOG642 の前提（確かめ）", 'urdf', 10.0)
run("カタログの重さ・足りない分は付け根・制御箱はカタログ", 'base', 2.044)
run("カタログの重さ・各部を同じ割合で増やす・制御箱はカタログ", 'scale', 2.044)
