/**
 * Browser-only Tesseract.js wrapper. The WASM bundle is ~5 MB so we
 * lazy-import on first use; subsequent scans reuse the cached module.
 *
 * Tesseract runs entirely in the browser - no image data leaves the
 * user's device on this code path. AI providers (OpenAI/Claude) are
 * a separate, opt-in path that runs server-side.
 */

import type { ParsedReceipt } from '@/lib/services/ocr-providers';
import { parseReceiptText } from '@/lib/ocr/parse-receipt-text';

interface TesseractRunResult {
  parsed: ParsedReceipt;
  rawText: string;
  /** 0–100 mean per-word confidence reported by Tesseract. */
  confidence: number;
}

/** Lazy-imports tesseract.js and runs OCR on `file`. */
export async function runTesseract(file: File): Promise<TesseractRunResult> {
  // Dynamic import - the ~5 MB tesseract bundle stays out of the main chunk.
  const { recognize } = await import('tesseract.js');

  const { data } = await recognize(file, 'eng');
  const rawText = data.text ?? '';
  const confidence = typeof data.confidence === 'number' ? data.confidence : 0;
  const parsed = parseReceiptText({ text: rawText, ocrConfidence: confidence });
  return { parsed, rawText, confidence };
}
