import { spawnSync } from "child_process";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ASSIMP_PATH = path.join(__dirname, "../../bin/model_converter.exe");

let importExts = null;
let exportFormats = null;

export function getImportExtensions() {
  if (!importExts) {
    const r = spawnSync(ASSIMP_PATH, ["listext"], { encoding: "utf8" });
    importExts = r.stdout.trim().split(";").map(e => e.replace("*", "").toLowerCase());
  }
  return importExts;
}

export function getExportFormats() {
  if (!exportFormats) {
    const r = spawnSync(ASSIMP_PATH, ["listexport"], { encoding: "utf8" });
    exportFormats = r.stdout.trim().split(/\r?\n/).filter(Boolean);
  }
  return exportFormats;
}

export async function convert(inputFile, outputFile, format, cwd = process.cwd()) {
  const r = spawnSync(ASSIMP_PATH, ["export", inputFile, outputFile, `-f${format}`], { encoding: "utf8", cwd });
  if (r.status !== 0) throw new Error(r.stderr || r.stdout || "转换失败");
  return outputFile;
}
