/** Typed API client for the Kerf Engine. */

import type { PresetsResponse, TraceResponse } from '../types/engine';

const BASE = '/engine';

/**
 * Fetch all available presets from the engine.
 */
export async function getPresets(signal?: AbortSignal): Promise<PresetsResponse> {
  const res = await fetch(`${BASE}/presets`, { signal });
  if (!res.ok) {
    throw new Error(`GET /engine/presets failed: ${res.status} ${res.statusText}`);
  }
  return res.json() as Promise<PresetsResponse>;
}

/**
 * Trace a raster image through the vectorization pipeline.
 * Builds FormData with the file, mode, preset, and JSON-encoded params.
 */
export async function traceImage(
  file: File,
  preset: string,
  params: Record<string, unknown>,
  signal?: AbortSignal,
): Promise<TraceResponse> {
  const form = new FormData();
  form.append('file', file);
  form.append('output_format', 'svg');
  form.append('preset', preset);
  form.append('params', JSON.stringify(params));

  const res = await fetch(`${BASE}/trace`, {
    method: 'POST',
    body: form,
    signal,
  });
  if (!res.ok) {
    const detail = await res.text().catch(() => res.statusText);
    throw new Error(`POST /engine/trace failed: ${res.status} — ${detail}`);
  }
  return res.json() as Promise<TraceResponse>;
}

/**
 * Simplify an existing SVG using RDP path simplification.
 */
export async function simplifyVector(
  file: File,
  epsilon: number,
  signal?: AbortSignal,
): Promise<TraceResponse> {
  const form = new FormData();
  form.append('file', file);
  form.append('epsilon', String(epsilon));
  form.append('output_format', 'svg');

  const res = await fetch(`${BASE}/simplify`, {
    method: 'POST',
    body: form,
    signal,
  });
  if (!res.ok) {
    const detail = await res.text().catch(() => res.statusText);
    throw new Error(`POST /engine/simplify failed: ${res.status} — ${detail}`);
  }
  return res.json() as Promise<TraceResponse>;
}
