/** 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>;
}

/**
 * Export an SVG as DXF via the engine's simplify endpoint.
 *
 * Posts the SVG content as a file with output_format=dxf, along with
 * units and scale_factor parameters. Returns the raw DXF binary as a Blob.
 */
export async function exportAsDxf(
  svgContent: string,
  units: 'inches' | 'mm',
  scaleFactor: number,
  signal?: AbortSignal,
): Promise<Blob> {
  const form = new FormData();
  form.append(
    'file',
    new Blob([svgContent], { type: 'image/svg+xml' }),
    'export.svg',
  );
  form.append('output_format', 'dxf');
  form.append('units', units);
  form.append('scale_factor', String(scaleFactor));

  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 (DXF export) failed: ${res.status} — ${detail}`);
  }
  return res.blob();
}
