import * as bindings from "./vectortracer_bg.js";

let readyPromise = null;

async function loadWasm() {
  if (readyPromise) return readyPromise;
  readyPromise = (async () => {
    const response = await fetch(new URL("./vectortracer_bg.wasm", import.meta.url), { cache: "force-cache" });
    if (!response.ok) throw new Error(`高质量曲线引擎加载失败（${response.status}）`);
    const bytes = await response.arrayBuffer();
    const imports = { "./vectortracer_bg.js": bindings };
    const { instance } = await WebAssembly.instantiate(bytes, imports);
    bindings.__wbg_set_wasm(instance.exports);
    instance.exports.__wbindgen_start();
    return bindings;
  })();
  return readyPromise;
}

async function traceBinary(imageData, options = {}) {
  if (!(imageData instanceof ImageData)) throw new TypeError("需要有效的文字或 Logo 图像区域");
  const api = await loadWasm();
  const toRadians = degrees => Number(degrees) * Math.PI / 180;
  const converter = new api.BinaryImageConverter(imageData, {
    debug: false,
    mode: "spline",
    cornerThreshold: toRadians(options.cornerThreshold ?? 60),
    lengthThreshold: Number(options.lengthThreshold ?? 2.5),
    maxIterations: Math.max(1, Math.min(20, Number(options.maxIterations ?? 10))),
    spliceThreshold: toRadians(options.spliceThreshold ?? 45),
    filterSpeckle: Math.max(0, Math.round(Number(options.filterSpeckle ?? 2))),
    pathPrecision: Math.max(1, Math.min(6, Math.round(Number(options.pathPrecision ?? 3))))
  }, {
    invert: false,
    pathFill: "#ffffff",
    backgroundColor: "transparent",
    // vectortracer concatenates this value directly after the style attribute.
    // Keep the leading space or the generated SVG becomes invalid XML.
    attributes: " data-engine=\"vtracer-spline\"",
    scale: 1
  });
  try {
    converter.init();
    return await new Promise((resolve, reject) => {
      const tick = () => {
        try {
          if (converter.tick()) resolve(converter.getResult());
          else window.setTimeout(tick, 0);
        } catch (error) { reject(error); }
      };
      window.setTimeout(tick, 0);
    });
  } finally {
    converter.free();
  }
}

window.JianglaiSplineTracer = Object.freeze({ load: loadWasm, traceBinary });
loadWasm().catch(error => console.warn("高质量曲线引擎暂未就绪：", error));
