/**
 * acadrust DWG parser wrapper — loads the wasm built from rust/dwg-wasm
 * (wasm-pack --target web, committed under ./acadrust-dwg).
 */
import init, { parse_dwg_json } from './acadrust-dwg/acadrust_dwg.js';
import wasmUrl from './acadrust-dwg/acadrust_dwg_bg.wasm?url';
import type { CadParseResult } from './dwgParser';

let ready: Promise<void> | null = null;

/** Initialize the acadrust WASM module once (idempotent). */
export function initAcadrustParser(): Promise<void> {
  if (!ready) ready = init({ module_or_path: wasmUrl }).then(() => undefined);
  return ready;
}

/**
 * Parse a DWG buffer. Requires initAcadrustParser() first.
 *
 * Goes through `parse_dwg_json` + `JSON.parse` rather than the `parse_dwg`
 * export that hands back a JsValue. The latter keeps the entire result live on
 * the wasm heap as it builds, and the allocator's cost grows with that heap —
 * a 19 MB drawing took ~354 s and froze the tab. Streaming the result out as
 * text keeps it linear: the same file now lands in ~2.5 s.
 */
export function parseDwgAcadrust(bytes: Uint8Array): CadParseResult {
  return JSON.parse(parse_dwg_json(bytes)) as CadParseResult;
}
