import { initVTracerWasm, vectorize_rgba } from "./vtracer_wasm.js";

let readyPromise = null;

function clamp(value, minimum, maximum) {
  return Math.max(minimum, Math.min(maximum, Number(value)));
}

function tracerOptions(options = {}) {
  const mode = String(options.mode || "logo");
  const boundaryMode = options.boundaryMode === "stacked" ? "stacked" : "cutout";
  const photoLike = mode === "photo";
  const lineLike = mode === "line";
  const packagingLike = mode === "packaging";
  const glyphOutline = options.preserveGlyphs === true;
  const semanticInkMask = options.semanticInkMask === true;
  const monochrome = (lineLike && !glyphOutline) || semanticInkMask;
  const requestedFit = String(options.traceFit || "").toLowerCase();
  const fitMode = ["pixel", "polygon", "spline"].includes(requestedFit)
    ? requestedFit
    : "spline";
  return {
    preset: monochrome ? "bw" : photoLike ? "photo" : "poster",
    clustering: monochrome ? "bw" : photoLike ? "watershed" : "color-cluster",
    hierarchical: boundaryMode,
    mode: fitMode,
    filterSpeckle: semanticInkMask ? 0 : Math.round(clamp(options.speckle ?? 4, 0, 80)),
    colorPrecision: photoLike || packagingLike ? 8 : 6,
    layerDifference: photoLike ? 8 : packagingLike ? 10 : 16,
    cornerThreshold: semanticInkMask ? 58 : lineLike ? 45 : packagingLike ? 50 : 60,
    lengthThreshold: semanticInkMask ? 1 : lineLike ? 2 : packagingLike ? 2 : 4,
    maxIterations: 10,
    spliceThreshold: 45,
    pathPrecision: fitMode === "pixel" ? 2 : semanticInkMask ? 5 : lineLike || packagingLike ? 4 : 3,
    maxColors: Math.round(clamp(options.colors ?? 8, 2, 32)),
    simplify: clamp(options.simplify ?? 1, 0, 4),
    optimize: 2,
    adaptive: monochrome,
    adaptiveT: lineLike ? 12 : 15,
    watershedDetail: photoLike ? Math.round(clamp(55 + Number(options.colors || 12) * 3, 65, 150)) : 100
  };
}

async function load() {
  if (!readyPromise) readyPromise = initVTracerWasm();
  return readyPromise;
}

async function trace(imageData, options = {}) {
  if (!imageData?.data || !imageData.width || !imageData.height) throw new Error("缺少可转换的像素数据");
  await load();
  const rgba = imageData.data instanceof Uint8Array
    ? imageData.data
    : new Uint8Array(imageData.data.buffer, imageData.data.byteOffset, imageData.data.byteLength);
  const mappedOptions = tracerOptions(options);
  const svg = vectorize_rgba(rgba, imageData.width, imageData.height, mappedOptions);
  if (!/<svg\b[\s\S]*<path\b/i.test(svg)) throw new Error("专业曲线引擎没有返回有效路径");
  return { svg, options: mappedOptions, engine: "vtracer-1.0" };
}

window.JianglaiProfessionalTracer = Object.freeze({
  load,
  trace,
  tracerOptions,
  version: "1.0.0-alpha.2"
});

load().catch(error => console.warn("Professional vector tracer warm-up failed", error));
