import { NodeIO } from '@gltf-transform/core';
import { KHRONOS_EXTENSIONS } from '@gltf-transform/extensions';
import { dedup, flatten, join, weld, prune, quantize } from '@gltf-transform/functions';

const [input, output] = process.argv.slice(2);
const io = new NodeIO().registerExtensions(KHRONOS_EXTENSIONS);
const doc = await io.read(input);

const before = doc.getRoot().listMeshes().reduce((n, m) => n + m.listPrimitives().length, 0);
await doc.transform(
  dedup(),                     // drop duplicate accessors/materials
  flatten(),                   // bake node transforms so far-apart parts can merge
  join({ keepNamed: false }),  // MERGE primitives sharing a material -> fewer draw calls
  weld(),                      // index + merge coincident verts
  prune(),                     // drop now-unused nodes/accessors/materials
  quantize(),                  // KHR_mesh_quantization (Babylon-native, no decoder; NOT draco)
);
const after = doc.getRoot().listMeshes().reduce((n, m) => n + m.listPrimitives().length, 0);

// Orientation fix: flatten/join re-express the KiCad scene Y-up, but the wiki 3D
// viewer assumes Z-up (it rotates Z-up -> Y-up for display, like every other Adom
// GLB). Left Y-up, the board renders standing on edge. Rotate content +90deg about
// X (maps +Y -> +Z) so the board is Z-up and displays flat with parts pointing up.
const scene = doc.getRoot().getDefaultScene() || doc.getRoot().listScenes()[0];
const zup = doc.createNode('adom_zup').setRotation([0.70710678, 0, 0, 0.70710678]);
for (const child of scene.listChildren()) zup.addChild(child);
scene.addChild(zup);

await io.write(output, doc);
console.log(`primitives ${before} -> ${after}; applied Z-up rotation`);