"""Generic audit for a model-built walking mech. The collision logic is adapted from the walk check
(the Opus build's walk test: cross-body BVH overlap plus closed-mesh containment), generalized to read
bodies from the scene instead of meta.json.
Run: blender -b mech.blend -P audit.py -- <out.json> [frame_step]
Parts = mesh objects not named pilot_* or ground. Body of a part = nearest ancestor Empty named B_*,
else the top ancestor, else none (flagged orphan).
"""
import bpy, json, sys, time, math
import numpy as np
from mathutils import Vector
from mathutils.bvhtree import BVHTree

A = sys.argv[sys.argv.index('--') + 1:]
OUT = A[0]
STEP = int(A[1]) if len(A) > 1 else 4
SC = bpy.context.scene
t0 = time.time()
res = {}


def body_of(ob):
    p = ob.parent
    top = None
    while p is not None:
        if p.type == 'EMPTY' and p.name.startswith('B_'):
            return p.name
        top = p
        p = p.parent
    return top.name if top else None


meshes = [o for o in bpy.data.objects if o.type == 'MESH']
pilot = [o for o in meshes if o.name.startswith('pilot_')]
parts = [o for o in meshes if not o.name.startswith('pilot_') and o.name.lower() != 'ground']
bodies_of = {o.name: body_of(o) for o in parts}
orphans = [o.name for o in parts if bodies_of[o.name] is None]
bodies = sorted({b for b in bodies_of.values() if b})
empties_B = [o for o in bpy.data.objects if o.type == 'EMPTY' and o.name.startswith('B_')]
animated = [o.name for o in empties_B if o.animation_data and o.animation_data.action]
res['parts'] = len(parts)
res['pilot_parts'] = len(pilot)
res['bodies'] = len(bodies)
res['body_empties'] = len(empties_B)
res['animated_bodies'] = len(animated)
res['orphans'] = orphans[:20]
res['frame_range'] = [SC.frame_start, SC.frame_end]
SC.frame_set(1)
dg = bpy.context.evaluated_depsgraph_get()


def arrays(ob):
    ev = ob.evaluated_get(dg)
    me = ev.to_mesh()
    me.calc_loop_triangles()
    v = np.empty(len(me.vertices) * 3)
    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)


def wv(ob, v):
    M = np.array(ob.matrix_world)
    return v @ M[:3, :3].T + M[:3, 3]


LOCAL = {}
for o in parts + pilot:
    try:
        LOCAL[o.name] = arrays(o)
    except Exception:
        pass
res['ntris'] = int(sum(len(LOCAL[o.name][1]) for o in parts if o.name in LOCAL))

# ---- pilot and overall size
parts_ok = [o for o in parts if o.name in LOCAL and len(LOCAL[o.name][0])]
if parts_ok:
    allp = np.vstack([wv(o, LOCAL[o.name][0]) for o in parts_ok])
    lo, hi = allp.min(0), allp.max(0)
    res['mech_height_m'] = round(float(hi[2] - lo[2]), 2)
else:
    lo = hi = np.zeros(3)
    res['mech_height_m'] = 0
pl = [o for o in pilot if o.name in LOCAL and len(LOCAL[o.name][0])]
if pl:
    pts = np.vstack([wv(o, LOCAL[o.name][0]) for o in pl])
    res['pilot_height_m'] = round(float(pts[:, 2].max() - pts[:, 2].min()), 2)
    res['pilot_inside_mech'] = bool(np.all(pts.min(0) >= lo - 0.3) and np.all(pts.max(0) <= hi + 0.3))
else:
    res['pilot_height_m'] = 0
    res['pilot_inside_mech'] = False

# ---- rams
rams = []
names = {o.name: o for o in empties_B}
for n in sorted(names):
    if n.endswith('_barrel') and n.replace('_barrel', '_rod') in names:
        b, r = names[n], names[n.replace('_barrel', '_rod')]
        L = []
        for f in range(1, 49, 2):
            SC.frame_set(f)
            L.append((b.matrix_world.translation - r.matrix_world.translation).length)
        rams.append({'name': n[2:-7], 'min_m': round(min(L), 3), 'max_m': round(max(L), 3), 'stroke_cm': round((max(L) - min(L)) * 100, 1)})
res['rams'] = rams
res['rams_working'] = sum(1 for r in rams if r['stroke_cm'] >= 3.0)

# ---- seam: parent-relative pose at frame 1 vs 49; root bodies compare rotation and z only
seam = 0.0
SC.frame_set(1)
M1 = {o.name: o.matrix_local.copy() for o in empties_B}
W1 = {o.name: o.matrix_world.copy() for o in empties_B}
SC.frame_set(49)
for o in empties_B:
    if o.parent is None:
        d = o.matrix_world
        r0 = W1[o.name].to_3x3()
        e = max(abs(d.translation.z - W1[o.name].translation.z),
                max(abs(d.to_3x3()[i][j] - r0[i][j]) for i in range(3) for j in range(3)) * 0.5)
    else:
        d = o.matrix_local
        m1 = M1[o.name]
        e = max((d.translation - m1.translation).length,
                max(abs(d.to_3x3()[i][j] - m1.to_3x3()[i][j]) for i in range(3) for j in range(3)) * 0.5)
    seam = max(seam, e)
res['seam_mm'] = round(seam * 1000, 2)


def all_world(f):
    SC.frame_set(f)
    return {o.name: wv(o, LOCAL[o.name][0]) for o in parts_ok}


# ---- travel and ground
P1 = all_world(1)
c1 = np.vstack(list(P1.values())).mean(0) if P1 else np.zeros(3)
P49 = all_world(49)
c49 = np.vstack(list(P49.values())).mean(0) if P49 else np.zeros(3)
res['travel_m'] = round(float(np.linalg.norm((c49 - c1)[:2])), 2)
res['travel_dir_xy'] = [round(float(x), 2) for x in (c49 - c1)[:2]]
floor_by_frame = []
for f in range(1, 49):
    P = all_world(f)
    floor_by_frame.append(min(p[:, 2].min() for p in P.values()) if P else 0.0)
res['ground_min_mm'] = round(min(floor_by_frame) * 1000, 1)
res['ground_max_of_lowest_mm'] = round(max(floor_by_frame) * 1000, 1)
res['below_ground_frames'] = int(sum(1 for z in floor_by_frame if z < -0.01))
res['floating_frames'] = int(sum(1 for z in floor_by_frame if z > 0.05))

# ---- foot slide on planted frames (bodies with foot or toe in the name)
footbodies = sorted({b for b in bodies if 'foot' in b.lower() or 'toe' in b.lower()})
slide = {}
for fb in footbodies:
    fparts = [o.name for o in parts_ok if bodies_of[o.name] == fb]
    prev, worst, planted = None, 0.0, 0
    for f in range(1, 50):
        SC.frame_set(f)
        pts = np.vstack([wv(bpy.data.objects[n], LOCAL[n][0]) for n in fparts])
        zm = pts[:, 2].min()
        if zm < 0.01:
            planted += 1
            xy = pts[pts[:, 2] < zm + 0.003][:, :2].mean(0)
            if prev is not None:
                worst = max(worst, float(np.linalg.norm(xy - prev)))
            prev = xy
        else:
            prev = None
    slide[fb] = {'max_step_cm': round(worst * 100, 2), 'planted_frames': planted}
res['foot_slide'] = slide
res['foot_slide_max_cm'] = max([v['max_step_cm'] for v in slide.values()] or [999])
res['planted_min_frames'] = min([v['planted_frames'] for v in slide.values()] or [0])

# ---- collisions across frames
frames = list(range(1, 49, STEP))
collisions = []
pair_tests = 0
min_clear = {}
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):
    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


names_p = [o.name for o in parts_ok if bodies_of[o.name]]
done_frames = 0
for f in frames:
    if time.time() - t0 > 700 or len(names_p) < 2:
        res['collision_timeout_at_frame'] = f
        break
    SC.frame_set(f)
    W = {n: (wv(bpy.data.objects[n], LOCAL[n][0]), LOCAL[n][1]) for n in names_p}
    lo_ = np.array([W[n][0].min(0) for n in names_p])
    hi_ = np.array([W[n][0].max(0) for n in names_p])
    bd = [bodies_of[n] for n in names_p]
    M = 0.02
    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_p[i], names_p[j]
        if bd[i] == bd[j]:
            continue
        pair_tests += 1
        ta, tb = tree(a), tree(b)
        hit = ta.overlap(tb)
        inside = False
        if not hit:
            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:
            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) // 100)]:
                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)
    done_frames += 1

pairs = {}
for c in collisions:
    k = (c['a'], c['b'])
    pairs[k] = pairs.get(k, 0) + 1
res['collisions'] = len(collisions)
res['collision_pairs'] = len(pairs)
res['collision_top'] = [[k[0], k[1], v] for k, v in sorted(pairs.items(), key=lambda kv: -kv[1])[:60]]
cl = sorted(((v[0], k, v[1]) for k, v in min_clear.items()))
res['closest_mm'] = [(round(d * 1000, 1), k[0], k[1], fr) for d, k, fr in cl[:20]]
res['pair_tests'] = pair_tests
res['frames_checked'] = done_frames
res['audit_seconds'] = round(time.time() - t0, 1)
json.dump(res, open(OUT, 'w'), indent=1)
print('AUDIT DONE parts', res['parts'], 'collision pairs', res['collision_pairs'])
