import { ref as c, reactive as d, watch as m } from "vue";
import { useTimeoutPoll as g, whenever as v } from "@vueuse/core";
import { getRawPlatformaInstance as w } from "@platforma-sdk/model";
const h = "[==PROGRESS==]";
function P(t) {
  return t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function O(t) {
  const r = c(), n = d({
    errorCount: 0
  });
  async function s() {
    var l;
    let e = r.value;
    if (e === void 0) return;
    const o = t.mockPlatforma ?? w();
    if (!o) {
      console.warn("Platforma API is not available");
      return;
    }
    for (; ; ) {
      const a = await o.logDriver.readText(e.logHandle, 100, e.lastOffset);
      if (e.error = void 0, n.errorCount = 0, a.shouldUpdateHandle || e.logHandle !== ((l = r.value) == null ? void 0 : l.logHandle)) return;
      const f = t.progressPrefix ?? h, u = new TextDecoder().decode(a.data).replace(new RegExp(`${P(f)}`, "g"), "");
      if (e = Object.assign(e, {
        lines: e.lines + u,
        lastOffset: a.newOffset,
        finished: !a.live
      }), a.newOffset >= a.size) break;
    }
  }
  const i = g(() => s().catch((e) => {
    r.value && (n.errorCount++, n.errorCount > (t.maxRetries ?? 3) ? r.value.error = e : console.warn("skip error:", e, "retry..."));
  }), 1500, { immediate: !1, immediateCallback: !0 });
  return v(
    () => {
      var e;
      return (e = r == null ? void 0 : r.value) == null ? void 0 : e.finished;
    },
    () => i.pause()
  ), m(
    () => t.logHandle,
    (e) => {
      var o;
      e === void 0 ? (r.value = void 0, i.pause()) : e !== ((o = r.value) == null ? void 0 : o.logHandle) && (r.value = { logHandle: e, lastOffset: 0, lines: "", finished: !1, error: void 0 }, n.errorCount = 0, i.resume());
    },
    { immediate: !0 }
  ), r;
}
export {
  O as useLogHandle
};
//# sourceMappingURL=useLogHandle.js.map
