export interface Vertex {
  x: number;
  y: number;
  z: number;
}

export interface Face {
  indices: number[];
}

export interface BoundingBox {
  min: Vertex;
  max: Vertex;
}

export interface Mesh {
  vertices: Vertex[];
  faces: Face[];
}

export function parseOBJ(text: string): Mesh {
  const vertices: Vertex[] = [];
  const faces: Face[] = [];

  for (const line of text.split('\n')) {
    const trimmed = line.trim();
    if (trimmed.startsWith('#') || trimmed === '') continue;

    const parts = trimmed.split(/\s+/);
    const type = parts[0];

    if (type === 'v') {
      vertices.push({
        x: parseFloat(parts[1]),
        y: parseFloat(parts[2]),
        z: parseFloat(parts[3]),
      });
    } else if (type === 'f') {
      const indices = parts.slice(1).map((p) => {
        const idx = parseInt(p.split('/')[0], 10);
        return idx - 1; // OBJ is 1-indexed
      });
      faces.push({ indices });
    }
  }

  return { vertices, faces };
}

export function computeBoundingBox(vertices: Vertex[]): BoundingBox {
  if (vertices.length === 0) {
    return {
      min: { x: 0, y: 0, z: 0 },
      max: { x: 0, y: 0, z: 0 },
    };
  }

  const min = { x: Infinity, y: Infinity, z: Infinity };
  const max = { x: -Infinity, y: -Infinity, z: -Infinity };

  for (const v of vertices) {
    min.x = Math.min(min.x, v.x);
    min.y = Math.min(min.y, v.y);
    min.z = Math.min(min.z, v.z);
    max.x = Math.max(max.x, v.x);
    max.y = Math.max(max.y, v.y);
    max.z = Math.max(max.z, v.z);
  }

  return { min, max };
}
