import { ref } from "vue";
export function useTesseract(options = {}) {
  const progress = ref(0);
  const status = ref("idle");
  const lang = options.lang ?? "ocrb";
  const langPath = options.langPath ?? "/tesseract/";
  let lib = null;
  function resolvedLangPath() {
    if (!import.meta.client)
      return langPath;
    return new URL(langPath, window.location.origin).toString();
  }
  async function ensureReady() {
    if (!import.meta.client)
      throw new Error("Tesseract OCR is client-only.");
    if (!lib) {
      lib = await import("tesseract.js");
    }
    return lib;
  }
  async function recognize(canvas) {
    const tesseract = await ensureReady();
    progress.value = 0;
    status.value = "starting";
    const result = await tesseract.recognize(canvas, lang, {
      gzip: true,
      cacheMethod: "refresh",
      langPath: resolvedLangPath(),
      logger: (m) => {
        if (m?.status)
          status.value = m.status;
        if (m?.status === "recognizing text" && typeof m?.progress === "number")
          progress.value = Math.round(m.progress * 100);
      }
    });
    status.value = "idle";
    return result?.data?.text || "";
  }
  return {
    progress,
    status,
    ensureReady,
    recognize
  };
}
