"""Walk test for the Mossback mech: every part against every part on every other
body, on every frame; foot slide; ground contact; piston engagement; joint
integrity.  Run:  blender -b <06_walk.blend> -P check.py -- <meta.json> <out.json> [frame_step]
"""
import bpy, json, sys, time
import numpy as np
from mathutils import Vector, Matrix
from mathutils.bvhtree import BVHTree

ARGS = sys.argv[sys.argv.index('--') + 1:]
META = json.load(open(ARGS[0]))
OUTP = ARGS[1]
STEP = int(ARGS[2]) if len(ARGS) > 2 else 1
NF = META['nf']
SC = bpy.context.scene
t0 = time.time()

parts = [p for p in META['parts'] if p['kind'] != 'decal']
obs = {p['name']: bpy.data.objects[p['name']] for p in parts}
body_of = {p['name']: p['body'] for p in parts}
rigid = [p['name'] for p in parts if p['kind'] != 'hose']
flex = [p['name'] for p in parts if p['kind'] == 'hose']

dg = bpy.context.evaluated_depsgraph_get()


def mesh_arrays(ob):
    ev = ob.evaluated_get(dg)
    me = ev.to_mesh()
    me.calc_loop_triangles()
    v = np.empty(len(me.vertices) * 3, dtype=np.float64)
    me.vertices.foreach_get('co', v)
    t = np.empty(len(me.loop_triangles) * 3, dtype=np.int32)
    me.loop_triangles.foreach_get('vertices', t)
    ev.to_mesh_clear()
    return v.reshape(-1, 3), t.reshape(-1, 3)


SC.frame_set(0)
dg = bpy.context.evaluated_depsgraph_get()
LOCAL = {n: mesh_arrays(obs[n]) for n in rigid}
ntris = sum(len(LOCAL[n][1]) for n in rigid)
print('parts', len(parts), 'rigid', len(rigid), 'flex', len(flex), 'tris', ntris)


def world(n, M):
    v, t = LOCAL[n]
    A = np.array(M)
    return v @ A[:3, :3].T + A[:3, 3], t


def aabb(v):
    return v.min(0), v.max(0)


DIRS = [Vector((0.123, 0.456, 0.880)).normalized(), Vector((-0.71, 0.33, -0.62)).normalized(), Vector((0.2, -0.9, 0.38)).normalized()]


def parity_inside(tree, p):
    # a point is inside a closed part when rays in every test direction cross it an odd number of times
    for d in DIRS:
        o = p.copy()
        n = 0
        for _ in range(64):
            loc, nrm, idx, dist = tree.ray_cast(o, d)
            if loc is None:
                break
            n += 1
            o = loc + d * 1e-5
        if n % 2 == 0:
            return False
    return True


collisions = []
pair_tests = 0
bvh_tests = 0
min_clear = {}
frames = list(range(0, NF, STEP))
for f in frames:
    SC.frame_set(f)
    dg = bpy.context.evaluated_depsgraph_get()
    W = {}
    for n in rigid:
        W[n] = world(n, obs[n].matrix_world)
    for n in flex:
        W[n] = mesh_arrays(obs[n])
        A = np.array(obs[n].matrix_world)
        W[n] = (W[n][0] @ A[:3, :3].T + A[:3, 3], W[n][1])
    names = list(W.keys())
    lo = np.array([W[n][0].min(0) for n in names])
    hi = np.array([W[n][0].max(0) for n in names])
    bodies = [body_of[n] for n in names]
    M = 0.03
    ov = np.all((lo[:, None, :] - M <= hi[None, :, :]) & (lo[None, :, :] - M <= hi[:, None, :]), axis=2)
    ii, jj = np.nonzero(np.triu(ov, 1))
    trees = {}

    def tree(n):
        if n not in trees:
            v, t = W[n]
            trees[n] = BVHTree.FromPolygons([tuple(x) for x in v], [tuple(x) for x in t], all_triangles=True)
        return trees[n]
    for i, j in zip(ii, jj):
        a, b = names[i], names[j]
        if bodies[i] == bodies[j]:
            continue
        pair_tests += 1
        ta, tb = tree(a), tree(b)
        bvh_tests += 1
        hit = ta.overlap(tb)
        inside = False
        if not hit:
            # containment: a vertex of one part inside the other (closed meshes)
            for (x, y, tx) in ((a, b, tb), (b, a, ta)):
                vx = W[x][0]
                blo, bhi = W[y][0].min(0), W[y][0].max(0)
                sel = vx[np.all((vx >= blo) & (vx <= bhi), axis=1)]
                for p in sel[:: max(1, len(sel) // 40)]:
                    if parity_inside(tx, Vector(p)):
                        inside = True
                        break
                if inside:
                    break
        if hit or inside:
            collisions.append({'frame': f, 'a': a, 'b': b, 'tris': len(hit), 'inside': inside})
        else:
            # clearance (sampled vertices of the smaller part to the other surface)
            x, y = (a, b) if len(W[a][0]) < len(W[b][0]) else (b, a)
            ty = tree(y)
            best = 9.0
            vx = W[x][0]
            for p in vx[:: max(1, len(vx) // 150)]:
                loc, nrm, idx, d = ty.find_nearest(Vector(p), 0.03)
                if loc is not None and d < best:
                    best = d
            key = tuple(sorted((a, b)))
            if best < min_clear.get(key, (9.0, 0))[0]:
                min_clear[key] = (best, f)
    if f % 24 == 0:
        print('frame', f, 'collisions so far', len(collisions), '%.0fs' % (time.time() - t0))

# ---------------- foot slide and ground contact
SC.frame_set(0)
slide = {}
ground_min = 9.0
pen_frames = 0
for s in ('L', 'R'):
    st = META['stance'][s]
    foot = bpy.data.objects['B_foot_' + s]
    pad_names = [n for n in rigid if n.startswith('foot_' + s + '.') and ('pad' in n)]
    run_start = None
    worst = 0.0
    for f in range(NF + 1):
        on = st[f % NF] if f < NF else False
        if on:
            SC.frame_set(f)
            Mw = foot.matrix_world.copy()
            pts = []
            for n in pad_names:
                v, _ = LOCAL[n]
                ob = obs[n]
                A = np.array(ob.matrix_world)
                w = v @ A[:3, :3].T + A[:3, 3]
                pts.append(w[w[:, 2] < w[:, 2].min() + 0.002])
            pts = np.vstack(pts)
            if run_start is None:
                run_start = pts
            else:
                d = np.linalg.norm(pts - run_start, axis=1).max()
                worst = max(worst, d)
        else:
            run_start = None
    slide[s] = worst
for f in range(NF):
    SC.frame_set(f)
    for s in ('L', 'R'):
        for n in rigid:
            if n.startswith('foot_' + s + '.'):
                v, _ = LOCAL[n]
                A = np.array(obs[n].matrix_world)
                z = (v @ A[:3, :3].T + A[:3, 3])[:, 2].min()
                ground_min = min(ground_min, z)
                if z < -0.0005:
                    pen_frames += 1

# ---------------- pistons and joints
eng_min, bot_min, misalign = 9.0, 9.0, 0.0
piston_rows = []
for p in META['pistons']:
    bar = bpy.data.objects['B_' + p['name'] + '_barrel']
    rod = bpy.data.objects['B_' + p['name'] + '_rod']
    emin, bmin = 9.0, 9.0
    for f in range(NF):
        SC.frame_set(f)
        PA = bar.matrix_world.translation
        PB = rod.matrix_world.translation
        D = (PA - PB).length
        e = p['Lr'] + p['Lb'] - D
        b = D - p['Lr'] - (p['z0'] + 0.025)
        za = bar.matrix_world.to_3x3().col[2]
        zb = rod.matrix_world.to_3x3().col[2]
        misalign = max(misalign, za.angle(-zb))
        emin, bmin = min(emin, e), min(bmin, b)
    piston_rows.append({'name': p['name'], 'stroke_cm': round((p['Dmax'] - p['Dmin']) * 100, 1),
                        'engage_min_cm': round(emin * 100, 1), 'bottom_clear_min_cm': round(bmin * 100, 1)})
    eng_min, bot_min = min(eng_min, emin), min(bot_min, bmin)

L1, L2 = 1.2, 1.2
joint_err = 0.0
for f in range(NF):
    SC.frame_set(f)
    for s, sg in (('L', 1), ('R', -1)):
        Mh = bpy.data.objects['B_hull'].matrix_world
        Mt = bpy.data.objects['B_thigh_' + s].matrix_world
        Ms = bpy.data.objects['B_shin_' + s].matrix_world
        Mx = bpy.data.objects['B_spider_' + s].matrix_world
        Mf = bpy.data.objects['B_foot_' + s].matrix_world
        errs = [
            (Mh @ Vector((0, 0.85 * sg, 0)) - Mt.translation).length,
            (Mt @ Vector((0, 0, -L1)) - Ms.translation).length,
            (Ms @ Vector((0, 0, -L2)) - Mx.translation).length,
            (Mx @ Vector((0, 0, -0.19)) - Mf.translation).length,
            # hinge axes must stay parallel: angle between thigh Y and shin Y (rad -> m at 0.2 m)
            Mt.to_3x3().col[1].angle(Ms.to_3x3().col[1]) * 0.2,
            Ms.to_3x3().col[1].angle(Mx.to_3x3().col[1]) * 0.2,
            Mx.to_3x3().col[0].angle(Mf.to_3x3().col[0]) * 0.2,
        ]
        joint_err = max(joint_err, max(errs))

cl = sorted(((v[0], k, v[1]) for k, v in min_clear.items()))
res = {
    'frames_checked': len(frames), 'parts_checked': len(parts), 'rigid_parts': len(rigid), 'flexible_parts': len(flex),
    'triangles': int(ntris), 'cross_body_pair_tests': pair_tests,
    'collisions': len(collisions), 'collision_list': collisions[:200],
    'collision_pairs': sorted({(c['a'], c['b']) for c in collisions}),
    'closest_clearances_mm': [(round(d * 1000, 1), k[0], k[1], fr) for d, k, fr in cl[:25]],
    'foot_slide_cm': {k: round(v * 100, 4) for k, v in slide.items()},
    'ground_min_mm': round(ground_min * 1000, 2), 'ground_penetration_foot_frames': pen_frames,
    'pistons': piston_rows, 'piston_engage_min_cm': round(eng_min * 100, 1), 'piston_bottom_clear_min_cm': round(bot_min * 100, 1),
    'piston_axis_misalign_deg': round(np.degrees(misalign), 4),
    'joint_error_mm': round(joint_err * 1000, 4),
    'seconds': round(time.time() - t0, 1),
}
json.dump(res, open(OUTP, 'w'), indent=1)
print('RESULT collisions', len(collisions), 'pairs', len(res['collision_pairs']))
for pr in res['collision_pairs'][:40]:
    n = sum(1 for c in collisions if (c['a'], c['b']) == tuple(pr))
    print('  HIT', pr, 'frames', n)
print('slide', res['foot_slide_cm'], 'ground_min_mm', res['ground_min_mm'], 'pen', pen_frames)
print('engage_min', res['piston_engage_min_cm'], 'bottom', res['piston_bottom_clear_min_cm'], 'misalign', res['piston_axis_misalign_deg'], 'joint_err_mm', res['joint_error_mm'])
print('closest', res['closest_clearances_mm'][:12])
print('seconds', res['seconds'])
