#!/usr/bin/env python3
"""An alternate foot-placement-aware controller for the existing articulated MuJoCo model.
Real forward dynamics: no external force or scripted root trajectory.
"""
import json,sys,math,pathlib,dataclasses
import numpy as np
from forward import MODEL,M,G,MAXTORQUE,QIDS,VIDS,contact_forces,BIDS,CONTACT_NAMES,contact_forces
import mujoco
BASE=pathlib.Path(__file__).resolve().parent
from dataclasses import dataclass
@dataclass
class FootParams:
  step_s:float=.32
  target_height:float=.91
  stride:float=.44
  foot_apex:float=.18
  stance_ahead:float=.19
  anklez:float=.125
  hipkp:float=250
  kneekp:float=320
  anklekp:float=145
  hipkd:float=32
  kneekd:float=28
  anklekd:float=12
  pitchkp:float=2.0
  pitchkd:float=.5
  speed:float=1.4
  # For target phase: first left stance from t0 until next footstep
  phase_s:float=0.
  # knee push-off can actively extend leg at late stance
  pushoff:float=.02
def ik(dx,dz):
  l1=.43;l2=.40
  r=math.hypot(dx,dz)
  r=min(max(r,.15),l1+l2-.009)
  knee=math.acos(max(-1,min(1,(r*r-l1*l1-l2*l2)/(2*l1*l2))))
  direction=math.atan2(-dx,-dz)
  h=direction-math.atan2(l2*math.sin(knee),l1+l2*math.cos(knee))
  return h,knee
def smooth(u):
  u=max(0.,min(1.,u))
  return u*u*(3-2*u)
def compute_ctrl(d,p):
  pelvisx=d.qpos[0]
  pelvis_z=.95+d.qpos[1]
  phase=(d.time+p.phase_s)/p.step_s
  step=int(math.floor(phase))
  within=phase-step
  stance_leg=step%2
  x_footbase=(step+0)*p.stride+p.stance_ahead
  # initial x-axis aligned with the original toe contact
  out=np.zeros(6)
  for side in range(2):
    is_stance=side==stance_leg
    if is_stance:
      # active stance controls a stable ankle target while COM advances across the foot.
      footx=x_footbase
      footz=p.anklez
      desired_pelvis_z=p.target_height
    else:
      # swing takes one foot from behind COM to in front of the next landing.
      # Schedule touchdown BEFORE nominal switch so the swing leg has
      # time to unload and settle. Flight clearance must vanish at u=1.
      u=smooth(min(1.0,within/.72))
      footx=pelvisx+(u*p.stance_ahead+(1-u)*(-.32))
      footz=p.anklez +p.foot_apex*math.sin(math.pi*min(1.0,within/.72))
      desired_pelvis_z=p.target_height
    dx=footx-pelvisx;dz=footz-desired_pelvis_z
    h,knee=ik(dx,dz)
    # walk/swing orientation face forefoot forward, flat ankle in stance
    an=-h-knee # stance foot flat
    if not is_stance: an+=.07
    # late stance ankle push, but this controller still must obey torque constraints.
    if is_stance: an-=p.pushoff*within
    h+=p.pitchkp*d.qpos[2]+p.pitchkd*d.qvel[2]
    # Only hip/knee/ankle actuators. No direct root force, no force control.
    goal=np.array([h,knee,an])
    actual=d.qpos[QIDS[side*3:side*3+3]]
    vel=d.qvel[VIDS[side*3:side*3+3]]
    kp=np.array([p.hipkp,p.kneekp,p.anklekp])
    kd=np.array([p.hipkd,p.kneekd,p.anklekd])
    torques=kp*(goal-actual)-kd*vel
    out[side*3:side*3+3]=np.clip(torques,-MAXTORQUE[side*3:side*3+3],MAXTORQUE[side*3:side*3+3])
  return out
def run(p,seconds=3,capture=False):
  d=mujoco.MjData(MODEL);d.qpos[:]=0
  d.qpos[0]=0;d.qpos[1]=p.target_height-.95
  for side in range(2):
   if side==0:dx=p.stance_ahead;dz=p.anklez-p.target_height
   else:dx=-.32;dz=p.anklez+.03-p.target_height
   h,k=ik(dx,dz);a=-h-k
   d.qpos[3+3*side:6+3*side]=[h,k,a]
  d.qvel[:]=0;d.qvel[0]=p.speed
  mujoco.mj_forward(MODEL,d)
  mujoco.mj_subtreeVel(MODEL,d)
  com_vx_initial=float(d.subtree_linvel[BIDS['pelvis'],0]);com_x_initial=float(d.subtree_com[BIDS['pelvis'],0])
  positiveFxImpulse=negativeFxImpulse=heelImpulse=foreImpulse=0.0
  posE=negE=0.0;maxF=0;maxT=0;contacts=0;frames=[];mood=[];falls=None
  steps=round(seconds/MODEL.opt.timestep)
  for i in range(steps):
    u=compute_ctrl(d,p);d.ctrl[:]=u
    pow=u*d.qvel[VIDS]
    posE+=float(np.maximum(pow,0).sum())*MODEL.opt.timestep
    negE+=float(np.maximum(-pow,0).sum())*MODEL.opt.timestep
    maxT=max(maxT,float(np.max(abs(u))))
    mujoco.mj_step(MODEL,d)
    if capture:
      pergeom=contact_forces(d)
      totFx=sum(v[0] for v in pergeom.values())
      positiveFxImpulse+=max(totFx,0)*MODEL.opt.timestep
      negativeFxImpulse+=max(-totFx,0)*MODEL.opt.timestep
      heelImpulse+=sum(v[2] for name,v in pergeom.items() if name.endswith('heel'))*MODEL.opt.timestep
      foreImpulse+=sum(v[2] for name,v in pergeom.items() if name.endswith('forefoot'))*MODEL.opt.timestep
    z=.95+d.qpos[1];pitch=d.qpos[2]
    fall=(z<.54 or abs(pitch)>1.0 or not np.all(np.isfinite(d.qpos)))
    if i%8==0 or fall:
      f=contact_forces(d);net=sum((x for x in f.values()),np.zeros(3))
      maxF=max(maxF,float(net[2])/(M*G))
      contacts+=int(net[2]>30)
      mood.append((round(float(d.time),3),round(float(z),3),round(float(d.qvel[0]),2),round(float(pitch),2)))
      if capture:
        pos={name:np.round(d.xpos[id],4).tolist() for name,id in BIDS.items()}
        frames.append({'t':round(float(d.time),4),'x':round(float(d.qpos[0]),4),'z':round(float(z),4),
        'pitch':round(float(pitch),4),'vx':round(float(d.qvel[0]),3),'fz':round(float(net[2]),2),'fx':round(float(net[0]),2),
        'ankle_heel_toe_Fz_N':{name:round(float(v[2]),2) for name,v in f.items()},
        'joints':np.round(d.qpos[QIDS],3).tolist(),'torque_Nm':np.round(u,1).tolist(),'body':pos,
        'geom_pose':{str(geom):[round(float(q),5) for q in d.geom_xpos[geom]]+[round(float(q),5) for q in d.geom_xmat[geom].flatten()] for geom in range(1,MODEL.ngeom)}})
    if fall:falls=float(d.time);break
  dur=float(d.time)
  mujoco.mj_subtreeVel(MODEL,d)
  final_com_vx=float(d.subtree_linvel[BIDS['pelvis'],0]); final_com_x=float(d.subtree_com[BIDS['pelvis'],0])
  res={'duration':round(dur,3),'requested':seconds,'distance':round(float(d.qpos[0]),3),'vx_end':round(float(d.qvel[0]),3),'pelvis_z':round(float(z),3),'pitch':round(float(pitch),3),
       'total_positive_joint_work_J':round(posE,3),'total_negative_joint_work_J':round(negE,3),
       'peak_motor_Nm':round(maxT,1),'peak_Fz_BW':round(maxF,3),'contact_rate':round(contacts/max(1,i//8+1),3),
       'fallen':falls is not None,
       'COM_vx_initial':round(com_vx_initial,4),'COM_vx_final':round(final_com_vx,4),
       'COM_dx_m':round(final_com_x-com_x_initial,4),
       'ground_positive_horizontal_impulse_Ns':round(positiveFxImpulse,4) if capture else None,
       'ground_negative_horizontal_impulse_Ns':round(negativeFxImpulse,4) if capture else None,
       'ground_net_horizontal_impulse_Ns':round(positiveFxImpulse-negativeFxImpulse,4) if capture else None,
       'COM_linear_momentum_change_Ns':round(M*(final_com_vx-com_vx_initial),4),
       'heel_load_vertical_impulse_Ns':round(heelImpulse,4) if capture else None,
       'forefoot_load_vertical_impulse_Ns':round(foreImpulse,4) if capture else None,
       'noteworthy': 'Forward dynamics only, foot geom contact, no root force.'}
  return res,frames
if __name__=='__main__':
  p=FootParams()
  r,trace=run(p,3,True)
  print(json.dumps(r,indent=2))
  (BASE/'ik_trial.json').write_text(json.dumps({'params':vars(p),'metrics':r,'frames':trace},indent=1))
