import { describe, it, expect, beforeAll } from 'vitest';
import { readFileSync } from 'node:fs';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createRequire } from 'node:module';

const __dirname = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);

interface WasmModule {
  loadMeshFromOBJ(obj: string): number;
  generateTestSphere(subdivisions: number): number;
  getCreaseEdges(handle: number, angleDeg: number): Float32Array;
  deleteMesh(handle: number): void;
}

let core: WasmModule;
const cubeOBJ = readFileSync(resolve(__dirname, '../fixtures/cube.obj'), 'utf-8');

beforeAll(async () => {
  const MeshLabCore = require(resolve(__dirname, '../../public/meshlab-core.cjs'));
  core = await MeshLabCore();
}, 10000);

describe('Crease Edge Detection', () => {
  it('detects all cube edges at 30 degree threshold', () => {
    const h = core.loadMeshFromOBJ(cubeOBJ);
    const edges = new Float32Array(core.getCreaseEdges(h, 30));
    // Cube has 12 edges, each edge = 2 vertices * 3 floats = 6 floats
    expect(edges.length).toBe(12 * 6);
    core.deleteMesh(h);
  });

  it('detects no edges at 180 degree threshold for smooth sphere', () => {
    const h = core.generateTestSphere(3);
    const edges = new Float32Array(core.getCreaseEdges(h, 180));
    expect(edges.length).toBe(0);
    core.deleteMesh(h);
  });

  it('detects some edges at 10 degree threshold for sphere', () => {
    const h = core.generateTestSphere(2);
    const edges = new Float32Array(core.getCreaseEdges(h, 10));
    // Low subdivision sphere has many creases at low threshold
    expect(edges.length).toBeGreaterThan(0);
    core.deleteMesh(h);
  });
});
