"""Bob Helper MuJoCo model (programmatic MJCF). Wheeled diff-drive base + lead-screw lift + torso/head + 2x 6-DOF arms
with 1-DOF parallel grippers. Design study, unbuilt, sim-only. Units SI. Original model (not derived from Asimov)."""
import math
# variant parameters
M50 = dict(peak=16.4, cont=6.8, w_nl=33.5, arm=0.0206, mass=0.35)
STS3250 = dict(peak=4.90, cont=1.57, w_nl=7.85, arm=0.01, mass=0.0745)
STS3215 = dict(peak=2.94, cont=0.98, w_nl=4.71, arm=0.01, mass=0.055)   # cont = 1/3 stall: assumption
VARIANTS = {
 "helper": dict(L1=0.30, L2=0.27, L3=0.13,
    act=dict(sp=M50, sr=M50, sy=M50, el=M50, wp=STS3250, wr=STS3215),
    m_upper=0.25, m_fore=0.20, m_hand=0.18, m_torso=2.1, m_base=6.0, m_col=1.6,
    label="Bob Helper (M50 arms)"),
 "helper_s": dict(L1=0.22, L2=0.20, L3=0.12,
    act=dict(sp=STS3250, sr=STS3250, sy=STS3215, el=STS3250, wp=STS3215, wr=STS3215),
    m_upper=0.12, m_fore=0.10, m_hand=0.15, m_torso=1.5, m_base=6.0, m_col=1.6,
    label="Bob Helper S (servo arms)"),
}
WHEEL_R, BASE_HX, BASE_HY, BASE_HZ, BASE_Z = 0.075, 0.25, 0.17, 0.05, 0.09
WHEEL_Y, CASTER_X, CASTER_Y, CASTER_R = 0.215, 0.23, 0.13, 0.025
CASTER_LIFT = 0.0
SUSP_K, SUSP_PRE = 8000.0, 0.008   # sprung drive wheels: 8 N/mm, 8 mm preload -> ~64 N per wheel keeps traction (all 4 casters touch)
BATT_KG, BATT_X = 1.83, -0.17   # 24x P42A (70 g) + BMS/wiring, mounted at the rear as ballast
SH_Z0, LIFT_MAX, SH_Y, SH_X, TORSO_X = 0.55, 0.43, 0.20, 0.02, 0.0   # shoulder height at lift 0; stroke; shoulder offsets
LIFT_F = 300.0      # N cap: 5010 direct on TR8x2 at 25 W copper loss, eta 0.35 (see design)
GRIP_F = 30.0       # N per finger, STS3215 torque-limited on 12 mm pinion
def arm_xml(v, side):
    s = 1 if side == "left" else -1; p = f"{side}_"
    L1, L2, L3, A = v["L1"], v["L2"], v["L3"], v["act"]
    rr = f"{-0.4 if s > 0 else -1.6} {1.6 if s > 0 else 0.4}"
    return f"""
   <body name="{p}shoulder" pos="{SH_X} {s*SH_Y} 0">
    <joint name="{p}sp" axis="0 1 0" range="-3.1 1.0" armature="{A['sp']['arm']}" damping="0.3"/>
    <geom type="cylinder" size="0.045 0.03" euler="90 0 0" mass="{A['sr']['mass']}" rgba=".15 .15 .15 1"/>
    <body name="{p}upper">
     <joint name="{p}sr" axis="1 0 0" range="{rr}" armature="{A['sr']['arm']}" damping="0.3"/>
     <joint name="{p}sy" axis="0 0 1" range="-1.6 1.6" armature="{A['sy']['arm']}" damping="0.3"/>
     <geom type="cylinder" size="0.04 0.025" pos="0 0 -0.05" mass="{A['sy']['mass']}" rgba=".15 .15 .15 1"/>
     <geom type="capsule" fromto="0 0 -0.06 0 0 {-L1+0.04}" size="0.03" mass="{v['m_upper']}" rgba=".78 .96 .26 1"/>
     <geom type="cylinder" size="0.04 0.03" pos="0 0 {-L1}" euler="90 0 0" mass="{A['el']['mass']}" rgba=".15 .15 .15 1"/>
     <body name="{p}fore" pos="0 0 {-L1}">
      <joint name="{p}el" axis="0 1 0" range="-2.4 0.05" armature="{A['el']['arm']}" damping="0.2"/>
      <geom type="capsule" fromto="0 0 -0.04 0 0 {-L2+0.03}" size="0.025" mass="{v['m_fore']}" rgba=".78 .96 .26 1"/>
      <geom type="box" size="0.02 0.025 0.02" pos="0 0 {-L2+0.01}" mass="{A['wp']['mass']}" rgba=".15 .15 .15 1"/>
      <body name="{p}wrist" pos="0 0 {-L2}">
       <joint name="{p}wp" axis="0 1 0" range="-1.8 1.8" armature="{A['wp']['arm']}" damping="0.05"/>
       <geom type="cylinder" size="0.02 0.015" mass="{A['wr']['mass']}" rgba=".15 .15 .15 1"/>
       <body name="{p}hand">
        <joint name="{p}wr" axis="0 0 1" range="-3.14 3.14" armature="{A['wr']['arm']}" damping="0.05"/>
        <geom type="box" size="0.03 0.045 0.025" pos="0 0 -0.03" mass="{v['m_hand']}" rgba=".3 .3 .3 1"/>
        <site name="{p}cam" pos="0.035 0 -0.03" size="0.008" rgba="0.2 0.4 1 1"/>
        <body name="{p}fa" pos="0 0.04 -0.09">
         <joint name="{p}ga" type="slide" axis="0 -1 0" range="0 0.045" limited="true" damping="20" armature="0.5"/>
         <geom name="{p}pad_a" type="box" size="0.022 0.006 0.035" mass="0.02" friction="0.5 0.01 0.001" condim="4" rgba=".2 .2 .2 1"/>
        </body>
        <body name="{p}fb" pos="0 -0.04 -0.09">
         <joint name="{p}gb" type="slide" axis="0 1 0" range="0 0.045" limited="true" damping="20" armature="0.5"/>
         <geom name="{p}pad_b" type="box" size="0.022 0.006 0.035" mass="0.02" friction="0.5 0.01 0.001" condim="4" rgba=".2 .2 .2 1"/>
        </body>
        <site name="{p}tip" pos="0 0 {-L3+0.03}" size="0.01" rgba="1 .2 .2 1"/>
        <body name="{p}payload" pos="0 0 -0.09"><geom type="box" size="0.03 0.03 0.03" mass="1e-6" contype="0" conaffinity="0" rgba=".9 .5 .1 .5"/></body>
       </body>
      </body>
     </body>
    </body>
   </body>"""
def build_xml(name="helper", obj=False, obj_mass=1.0, obj_pos=(0.6, 0.2, 0.5)):
    v = VARIANTS[name]
    acts = ""
    for side in ("left", "right"):
        for j in ("sp", "sr", "sy", "el", "wp", "wr"):
            pk = v["act"][j]["peak"]
            acts += f'<motor name="{side}_{j}" joint="{side}_{j}" ctrlrange="{-pk} {pk}" ctrllimited="true"/>\n'
        acts += f'<motor name="{side}_ga" joint="{side}_ga" ctrlrange="-60 60" ctrllimited="true"/><motor name="{side}_gb" joint="{side}_gb" ctrlrange="-60 60" ctrllimited="true"/>\n'
    for w in ("lw", "rw"):
        acts += f'<motor name="{w}" joint="{w}" ctrlrange="-16.4 16.4" ctrllimited="true"/>\n'
    acts += f'<motor name="lift" joint="lift" ctrlrange="{-LIFT_F} {LIFT_F}" ctrllimited="true"/>\n'
    for j in ("hp", "ht"): acts += f'<motor name="{j}" joint="{j}" ctrlrange="-2.94 2.94" ctrllimited="true"/>\n'
    objx = ""
    if obj:
        objx = f"""<body name="obj" pos="{obj_pos[0]} {obj_pos[1]} {obj_pos[2]}"><freejoint name="obj"/>
          <geom name="obj" type="box" size="0.03 0.03 0.03" mass="{obj_mass}" friction="0.5 0.01 0.001" condim="4" contype="3" conaffinity="3" rgba=".95 .55 .1 1"/></body>"""
    cz = -BASE_Z + CASTER_R + CASTER_LIFT
    casters = "".join(f'<geom name="caster{i}" type="sphere" size="{CASTER_R}" pos="{x} {y} {cz}" condim="1" mass="0.05" rgba=".3 .3 .3 1"/>'
                      for i, (x, y) in enumerate([(CASTER_X, CASTER_Y), (CASTER_X, -CASTER_Y), (-CASTER_X, CASTER_Y), (-CASTER_X, -CASTER_Y)]))
    col_h = SH_Z0 + LIFT_MAX + 0.08 - (BASE_Z + BASE_HZ)
    return f"""<mujoco model="bob_{name}">
 <compiler angle="radian" autolimits="true"/>
 <option timestep="0.001" integrator="implicitfast" cone="elliptic" impratio="10"/>
 <default><geom contype="2" conaffinity="1"/></default>
 <visual><headlight diffuse=".7 .7 .7" ambient=".3 .3 .3"/><global offwidth="1280" offheight="960"/></visual>
 <asset><texture name="grid" type="2d" builtin="checker" rgb1=".08 .08 .08" rgb2=".12 .12 .12" width="300" height="300" mark="edge" markrgb=".3 .5 .1"/>
  <material name="grid" texture="grid" texrepeat="8 8" reflectance=".1"/></asset>
 <worldbody>
  <light pos="1 -1 3" dir="-0.3 0.3 -1" diffuse=".8 .8 .8"/>
  <geom name="floor" type="plane" size="5 5 .1" material="grid" friction="0.8 0.01 0.001" contype="3" conaffinity="3"/>
  {objx}
  <body name="base" pos="0 0 {BASE_Z}"><freejoint name="base"/>
   <geom name="base" type="box" size="{BASE_HX} {BASE_HY} {BASE_HZ}" mass="{v['m_base'] - BATT_KG}" rgba=".1 .1 .1 1"/>
   <geom name="battery" type="box" size="0.07 0.09 0.035" pos="{BATT_X} 0 0" mass="{BATT_KG}" rgba=".2 .25 .6 1" contype="0" conaffinity="0"/>
   {casters}
   <geom name="column" type="box" size="0.03 0.05 {col_h/2}" pos="-0.12 0 {BASE_HZ + col_h/2}" mass="{v['m_col']}" rgba=".55 .55 .55 1"/>
   <body name="lw" pos="0 {WHEEL_Y} {WHEEL_R - BASE_Z}"><joint name="lw_susp" type="slide" axis="0 0 1" range="-0.012 0.012" stiffness="{SUSP_K}" springref="{-SUSP_PRE}" damping="300"/><joint name="lw" axis="0 1 0" damping="0.05" armature="0.0206"/>
    <geom type="cylinder" size="{WHEEL_R} 0.02" euler="1.5708 0 0" mass="0.6" friction="0.9 0.01 0.001" rgba=".2 .2 .2 1"/></body>
   <body name="rw" pos="0 {-WHEEL_Y} {WHEEL_R - BASE_Z}"><joint name="rw_susp" type="slide" axis="0 0 1" range="-0.012 0.012" stiffness="{SUSP_K}" springref="{-SUSP_PRE}" damping="300"/><joint name="rw" axis="0 1 0" damping="0.05" armature="0.0206"/>
    <geom type="cylinder" size="{WHEEL_R} 0.02" euler="1.5708 0 0" mass="0.6" friction="0.9 0.01 0.001" rgba=".2 .2 .2 1"/></body>
   <body name="torso" pos="{TORSO_X} 0 {SH_Z0 - BASE_Z}">
    <joint name="lift" type="slide" axis="0 0 1" range="0 {LIFT_MAX}" armature="2.0" damping="50"/>
    <geom name="torso" type="box" size="0.07 0.14 0.13" pos="-0.03 0 -0.03" mass="{v['m_torso']}" rgba=".1 .1 .1 1"/>
    <geom type="box" size="0.012 0.12 0.10" pos="0.045 0 -0.03" mass="0.01" rgba=".78 .96 .26 1" contype="0" conaffinity="0"/>
    <body name="head" pos="-0.02 0 0.19"><joint name="hp" axis="0 0 1" range="-1.6 1.6" damping="0.05"/><geom type="cylinder" size="0.02 0.02" pos="0 0 -0.06" mass="0.055" rgba=".15 .15 .15 1"/>
     <body name="headt"><joint name="ht" axis="0 1 0" range="-0.3 1.2" damping="0.05"/>
      <geom type="box" size="0.06 0.09 0.055" mass="0.35" rgba=".12 .12 .12 1"/>
      <geom type="box" size="0.005 0.07 0.02" pos="0.06 0 0.005" mass="0.001" rgba=".78 .96 .26 1" contype="0" conaffinity="0"/>
      <site name="headcam" pos="0.065 0 0.005" size="0.01"/></body></body>
    {arm_xml(v, "left")}
    {arm_xml(v, "right")}
   </body>
  </body>
 </worldbody>
 <contact></contact>
 <equality>
  <joint joint1="left_ga" joint2="left_gb"/><joint joint1="right_ga" joint2="right_gb"/>
 </equality>
 <actuator>
{acts} </actuator>
</mujoco>"""
ARMJ = ("sp", "sr", "sy", "el", "wp", "wr")
