import bpy, bmesh
from mathutils import Vector

SRC = "/Users/danicosta/Desktop/Avatar-Platon/3d_pipeline/oc_output/plato_medium.usdz"
bpy.ops.wm.read_factory_settings(use_empty=True)
scene = bpy.context.scene
bpy.ops.wm.usd_import(filepath=SRC)
meshes = [o for o in scene.objects if o.type == 'MESH']
for o in scene.objects: o.select_set(False)
for o in meshes: o.select_set(True)
bpy.context.view_layer.objects.active = meshes[0]
if len(meshes) > 1: bpy.ops.object.join()
head = bpy.context.active_object
bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY', center='BOUNDS')
head.location = (0, 0, 0)
head.scale = [2.2/max(head.dimensions)]*3
bpy.ops.object.transform_apply(scale=True)

bm = bmesh.new(); bm.from_mesh(head.data)
bm.verts.ensure_lookup_table(); bm.faces.ensure_lookup_table()

# componentes conexas por caras
seen = set(); islands = []
for f0 in bm.faces:
    if f0.index in seen: continue
    stack = [f0]; comp = []
    while stack:
        f = stack.pop()
        if f.index in seen: continue
        seen.add(f.index); comp.append(f)
        for e in f.edges:
            for nf in e.link_faces:
                if nf.index not in seen: stack.append(nf)
    islands.append(comp)

islands.sort(key=len, reverse=True)
print("ISLAS:", len(islands))
for i, comp in enumerate(islands[:8]):
    vs = set()
    for f in comp: vs.update(f.verts)
    zs = [v.co.z for v in vs]; ys=[v.co.y for v in vs]; xs=[v.co.x for v in vs]
    cz = sum(zs)/len(zs)
    print("isla %d: caras=%5d verts=%5d  z[%.2f,%.2f] cz=%.2f  y[%.2f,%.2f] x[%.2f,%.2f]" % (
        i, len(comp), len(vs), min(zs), max(zs), cz, min(ys), max(ys), min(xs), max(xs)))
bm.free()
