"""合体の3Dのページで使う、FR3 の姿勢（関節の角度）を逆算する。
座標：アームの付け根の底の中心から、前 f・右 r・上 u（m）。URDF では x=−f, y=r, z=u（付け根を 180° 回して付けるため）。
台座 300mm（付け根の底は地面から 0.698m）、つかむ道具 183mm。関節の範囲はカタログの値。
使い方: python3 arm_poses.py urdf_fixed <出力 json>"""
import sys, io, contextlib, math, json
import numpy as np
D_ = sys.argv[1]; sys.argv = [sys.argv[0], D_, sys.argv[2]]
src = open('arm_size_on_mitra.py', encoding='utf-8').read().split("f = lambda v: ' 倒れない'")[0]
ns = {}
with contextlib.redirect_stdout(io.StringIO()):
    exec(compile(src, 'arm_size_part', 'exec'), ns)
Arm, rz = ns['Arm'], ns['rz']
a = Arm('fairino3_v6.urdf', 15.0)
LIM = np.radians([[-175, 175], [-265, 85], [-150, 150], [-265, 85], [-175, 175], [-175, 175]])
TOOL = 0.150; BASE_H = 0.698   # 道具は吸着式 VGC10（吸盤の面まで 150mm・仮）。2本爪のときは 0.183 だった
def fk(q):
    M = np.eye(4); pts = []
    for (J, _, _), ang in zip(a.joints, q):
        M = M @ J @ rz(ang); pts.append(M[:3, 3].copy())
    fl = (M @ np.array([0, 0, 0.10, 1]))[:3]; tip = (M @ np.array([0, 0, 0.10 + TOOL, 1]))[:3]
    return pts, fl, tip, M[:3, 2].copy(), M[:3, 0].copy()
def to_u(f, r, u): return np.array([-f, r, u])
def solve(target, axis, seed):
    q = np.array(seed, float)
    for it in range(120):
        pts, fl, tip, ax, _ = fk(q)
        res = np.concatenate([tip - target, 0.3 * (ax - axis)])
        if np.linalg.norm(res[:3]) < 2e-4 and np.linalg.norm(ax - axis) < 2e-3: break
        Jm = np.zeros((6, 5))
        for k in range(5):
            d = q.copy(); d[k] += 1e-5; _, _, t2, a2, _ = fk(d)
            Jm[:, k] = (np.concatenate([t2 - target, 0.3 * (a2 - axis)]) - res) / 1e-5
        dq = np.linalg.lstsq(Jm.T @ Jm + 1e-7 * np.eye(5), -Jm.T @ res, rcond=None)[0]
        n = np.linalg.norm(dq)
        if n > 0.3: dq *= 0.3 / n
        q[:5] += dq; q = np.clip(q, LIM[:, 0], LIM[:, 1])
    pts, fl, tip, ax, _ = fk(q)
    ok = np.linalg.norm(tip - target) < 1e-3 and np.linalg.norm(ax - axis) < 1e-2
    return q, ok
SEEDS = [(j1, j2, j3, j4, j5, 0) for j1 in np.radians([0, 20, -20, 150, -150, 170, -170, 90, -90]) for j2, j3 in np.radians([[-60, 90], [-120, -90], [-100, 130], [-80, -130], [-30, 60], [-150, -60]])
         for j4 in np.radians([-135, -45, -90]) for j5 in np.radians([-90, 90])]
# ロボットの上の物（アームの付け根の座標・m）。箱：(f0,f1,r0,r1,u0,u1)
B = lambda b0, b1, r0, r1, h0, h1: ((0.065 - b1 / 1000), (0.065 - b0 / 1000), r0 / 1000, r1 / 1000, h0 / 1000 - 0.300, h1 / 1000 - 0.300)
OBST = {'台座': B(25, 105, -45, 45, 0, 285), '受けの板': B(0, 150, -200, 200, -40, 12), '荷台': B(0, 895, -200, 200, -60, 0),
        '後ろの山': B(700, 890, -180, 180, 0, 415), '柱（上カメラ）': B(865, 885, -180, -160, 0, 1125), '上カメラ': B(780, 885, -215, -125, 1090, 1125),
        'ライダー': B(10, 80, -190, -120, 12, 75)}
WALLS = (160, 690, 183, 178.5, 671.5, 167.5, 221)
def samples(q):
    pts, fl, tip, ax, xa = fk(q); out = []
    chain = pts[1:] + [fl]
    for p, p2 in zip(chain[:-1], chain[1:]):
        for t in np.linspace(0, 1, 7): out.append((p + (p2 - p) * t, 0.045))
    # 吸着式の道具：取り付け具（付け根から 10mm・半径 42）、本体（100×100×101 を球1つで・71mm・半径 52）、吸盤（130・140mm・半径 22）
    for z, rad in ((0.010, 0.042), (0.071, 0.052), (0.130, 0.022), (0.140, 0.022)): out.append((fl + (tip - fl) * (z / TOOL), rad))
    return out
def collide(q, box_open=True, extra=()):
    for p, rad in samples(q):
        f, r, u = -p[0], p[1], p[2]
        for name, (f0, f1, r0, r1, u0, u1) in list(OBST.items()) + list(extra):
            if f0 - rad < f < f1 + rad and r0 - rad < r < r1 + rad and u0 - rad < u < u1 + rad: return name
        if box_open:
            b0, b1, hw, ib0, ib1, ihw, H = WALLS; back = 0.065 - f; h = u + 0.300
            if h < H / 1000 + rad:
                o = (b0 / 1000 - rad < back < b1 / 1000 + rad) and abs(r) < hw / 1000 + rad
                i = (ib0 / 1000 + rad < back < ib1 / 1000 - rad) and abs(r) < ihw / 1000 - rad
                if o and not i: return '箱の壁'
    return None
def best(target, axis, prev, extra=(), box_open=True, family=None, stick=False):
    cands = []
    seeds = ([tuple(prev)] if prev is not None else []) + ([] if stick else SEEDS + OVER)
    for s in seeds:
        q, ok = solve(target, axis, s)
        if not ok: continue
        if family == 'over' and not (abs(q[0]) < math.radians(75) and q[1] < math.radians(-135)): continue
        if family == 'front' and not (abs(q[0]) < math.radians(60) and q[1] > math.radians(-135)): continue
        c = collide(q, box_open, extra)
        cost = (0 if c is None else 100) + (np.abs(q - prev).sum() if prev is not None else 0) + (0.5 if q[2] < 0 else 0)
        cands.append((cost, q, c))
    if not cands: return None, '届かない'
    cands.sort(key=lambda t: t[0]); return cands[0][1], cands[0][2]
OVER = [(j1, j2, j3, j4, 1.5708, 0) for j1 in np.radians([0, 25, -25, 50, -50]) for j2, j3 in np.radians([[-190, 90], [-170, 120], [-200, 60], [-185, 105], [-160, 140]]) for j4 in np.radians([-150, -190, -110])]
DOWN = np.array([0, 0, -1.0]); FWD = np.array([-1.0, 0, 0])
FOLD = np.radians([0, -125, 140, -105, -90, 0])
rng = np.random.default_rng(7)
def rand_seeds(n):
    out = []
    for _ in range(n):
        q = rng.uniform(LIM[:, 0], LIM[:, 1]); q[5] = 0; out.append(tuple(q))
    return out
def pair(name, pre_t, tgt_t, axis=DOWN, extra=(), family=None, nrand=50, ref=None):
    """手前の点（pre）と、つかむ・置く点（tgt）を、同じ腕の形のまま動ける組で探す"""
    ref = FOLD if ref is None else ref; best_ = None
    for sd in SEEDS + OVER + rand_seeds(nrand):
        q, ok = solve(to_u(*pre_t), axis, sd)
        if not ok or collide(q, True, extra) is not None: continue
        if family == 'over' and not (abs(q[0]) < math.radians(75) and q[1] < math.radians(-135)): continue
        if family == 'front' and not (abs(q[0]) < math.radians(60)): continue
        q2, ok2 = solve(to_u(*tgt_t), axis, tuple(q))
        if not ok2 or collide(q2, True, extra) is not None: continue
        if np.abs(q2 - q).max() > math.radians(100): continue
        cost = np.abs(q - ref).sum() + (0.6 if q[2] < 0 else 0) + 0.5 * np.abs(q2 - q).sum()
        if best_ is None or cost < best_[0]: best_ = (cost, q, q2)
    if best_ is None: print(name, '｜見つからない'); return None
    out[name + '_pre'] = best_[1].tolist(); out[name] = best_[2].tolist()
    print(name, '｜手前', np.degrees(best_[1]).round(1).tolist(), '｜点', np.degrees(best_[2]).round(1).tolist()); return best_[1]
out = {'fold': FOLD.tolist()}
print('fold ｜当たり', collide(FOLD), '｜爪先（前・右・上 mm）', (np.array([-1, 1, 1]) * fk(FOLD)[2] * 1000).round(0).tolist())
EX = 0.522 - 0.357      # 机のふち（荷台の前の端の 100mm 先）。アームの軸から
TABLE = [('机', (EX - 0.03, EX + 0.75, -0.75, 0.75, 0.740 - BASE_H - 0.03, 0.740 - BASE_H))]
STAND = [('立ち作業台', (EX - 0.03, EX + 0.9, -0.75, 0.75, 0.900 - BASE_H - 0.03, 0.900 - BASE_H))]
pair('table', (EX + 0.25, 0, 0.780 - BASE_H + 0.13), (EX + 0.25, 0, 0.780 - BASE_H), extra=TABLE, family='front')
pair('stand', (EX + 0.20, 0, 0.940 - BASE_H + 0.05), (EX + 0.20, 0, 0.940 - BASE_H), extra=STAND, family='front')
DOL = [('台車の箱の壁', (EX - 0.0, EX + 0.016, -0.265, 0.265, -BASE_H, 0.331 - BASE_H)), ('台車の箱の壁2', (EX + 0.350, EX + 0.366, -0.265, 0.265, -BASE_H, 0.331 - BASE_H))]
pair('dolly', (EX + 0.183, 0, 0.331 + 0.13 - BASE_H), (EX + 0.183, 0, 0.164 - BASE_H), extra=DOL, family='front')
SF = 0.572 - 0.357
SHELF = [('棚の板', (SF, SF + 0.45, -1.2, 1.2, 0.910 - BASE_H, 0.940 - BASE_H)), ('上の棚の板', (SF, SF + 0.45, -1.2, 1.2, 1.330 - BASE_H, 1.360 - BASE_H))]
pair('shelf', (SF + 0.15, 0, 0.990 - BASE_H), (SF + 0.33, 0, 0.990 - BASE_H), axis=FWD, extra=SHELF, family='front', nrand=120)
ITEM_POS = [(-150, -80), (-150, 80), (0, -80), (0, 80), (150, -80), (150, 80)]
prev = np.radians([0, -185, 105, -190, 90, 0])
for i, (ix, iz) in enumerate(ITEM_POS):
    f = 0.065 - 0.425 + ix / 1000; r = iz / 1000
    p = pair(f'box{i}', (f, r, 0.398 + 0.221 + 0.13 - BASE_H), (f, r, 0.452 - BASE_H), family='over', ref=prev, nrand=20)
    if p is None: p = pair(f'box{i}', (f, r, 0.398 + 0.221 + 0.13 - BASE_H), (f, r, 0.452 - BASE_H), ref=prev, nrand=60)
    if p is not None: prev = p
json.dump(out, open(sys.argv[2], 'w'), indent=1)
