import R, { setLogLevel as y, ExtensionSession as _ } from "./extension_js.js";
const g = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
  none: 4
};
let u = "error", m = null;
function E(r) {
  u = r, m && m(g[r]);
}
function x(r) {
  m = r, u !== "error" && r(g[u]);
}
function $(r) {
  return g[r] >= g[u];
}
function k(r, e = "info") {
  var t;
  if (r === null) return "null";
  if (r === void 0) return "undefined";
  if (typeof r == "string") return r;
  if (typeof r == "number" || typeof r == "boolean")
    return String(r);
  if (typeof r == "bigint") return `${r}n`;
  if (r instanceof Error) {
    const s = e === "debug" ? r.stack : (t = r.stack) == null ? void 0 : t.split(`
`)[0];
    return JSON.stringify({ message: r.message, name: r.name, stack: s });
  }
  if (typeof r == "function") return "[Function]";
  if (typeof r == "symbol") return String(r);
  if (typeof r == "object")
    try {
      return JSON.stringify(r);
    } catch (s) {
      return s instanceof TypeError && s.message.includes("circular") ? "[Circular]" : `[Unserializable: ${s instanceof Error ? s.message : String(s)}]`;
    }
  return String(r);
}
function I(r) {
  return `[extension-js][${r}]`;
}
function A(r, e) {
  if (!r) return "";
  const t = [];
  try {
    for (const [s, o] of Object.entries(r))
      t.push(`${s}=${k(o, e)}`);
  } catch {
    return " metadata=[unreadable]";
  }
  return t.length > 0 ? ` ${t.join(" ")}` : "";
}
function l(r, e) {
  return e.length === 0 ? { event: r } : e.length === 1 && typeof e[0] == "object" && e[0] !== null && !Array.isArray(e[0]) ? { event: r, metadata: e[0] } : {
    event: r,
    metadata: { _args: e.map((t) => k(t)).join(" ") }
  };
}
class h {
  constructor(e = "root") {
    this.namespace = e;
  }
  log(e, t, s) {
    try {
      if (!$(e)) return;
      const o = I(this.namespace), p = A(s, e), c = `${o} ${t}${p}`;
      switch (e) {
        case "debug":
          console.log(c);
          break;
        case "info":
          console.log(c);
          break;
        case "warn":
          console.warn(c);
          break;
        case "error":
          console.error(c);
          break;
        case "none":
          break;
        default: {
          const w = e;
          break;
        }
      }
    } catch {
    }
  }
  debug(e, ...t) {
    const { event: s, metadata: o } = l(e, t);
    this.log("debug", s, o);
  }
  info(e, ...t) {
    const { event: s, metadata: o } = l(e, t);
    this.log("info", s, o);
  }
  warn(e, ...t) {
    const { event: s, metadata: o } = l(e, t);
    this.log("warn", s, o);
  }
  error(e, ...t) {
    const { event: s, metadata: o } = l(e, t);
    this.log("error", s, o);
  }
  child(e) {
    return new h(`${this.namespace}.${e}`);
  }
  timer(e, t, s = "info") {
    const o = typeof performance < "u" && performance.now, p = o ? performance.now() : Date.now();
    return (c) => {
      try {
        const w = o ? performance.now() : Date.now(), S = Math.round(w - p), L = {
          ...t,
          ...c,
          duration_ms: S
        };
        this.log(s, e, L);
      } catch {
      }
    };
  }
}
const f = new h("root");
let a = null, b = !1;
const d = /* @__PURE__ */ new Map();
let i;
function T() {
  return Math.random().toString(36).slice(2) + Date.now().toString(36);
}
function j(r) {
  return r <= 0 ? "debug" : r === 1 ? "info" : r === 2 ? "warn" : r === 3 ? "error" : "none";
}
const W = self;
W.__extension_js_relay = (r) => (f.debug("relay", {
  action: r == null ? void 0 : r.action,
  runId: i
}), new Promise((e) => {
  const t = T();
  d.set(t, e), self.postMessage({
    type: "asyncRelay",
    id: t,
    command: r,
    runId: i
  });
}));
const M = /* @__PURE__ */ new Map();
function n(r, e) {
  M.set(r, e);
}
function B(r) {
  n("exists", (e) => r.fsExists(e)), n("stat", (e) => r.fsStat(e)), n("read", (e) => r.fsRead(e)), n("readText", (e) => r.fsReadText(e)), n("readBase64", (e) => r.fsReadBase64(e)), n("list", (e) => r.fsList(e)), n("mkdir", (e) => r.fsMkdir(e)), n("delete", (e) => r.fsDelete(e)), n("copy", (e) => r.fsCopy(e)), n("move", (e) => r.fsMove(e)), n("write", (e) => r.fsWrite(e)), n("writeText", (e) => r.fsWriteText(e)), n("writeBase64", (e) => r.fsWriteBase64(e)), n("append", (e) => r.fsAppend(e)), n("appendText", (e) => r.fsAppendText(e)), n("appendBase64", (e) => r.fsAppendBase64(e)), n("readRange", (e) => r.fsReadRange(e)), n("update", (e) => r.fsUpdate(e)), n("hash", (e) => r.fsHash(e));
}
async function C() {
  b || (await R(), a = new _(), y(3), x(y), B(a), b = !0);
}
C().then(() => {
  self.postMessage({ type: "ready" });
}).catch((r) => {
  const e = r instanceof Error ? r.message : String(r);
  self.postMessage({ type: "error", error: `WASM init failed: ${e}` });
});
self.onmessage = async (r) => {
  const e = r.data;
  if (e.type === "setLogLevel") {
    y(e.level), E(j(e.level)), f.debug("set_log_level", { level: e.level });
    return;
  }
  if (!b || !a) {
    self.postMessage({
      type: "error",
      id: e.id,
      error: "WASM not initialized"
    });
    return;
  }
  switch (e.type) {
    case "runCell": {
      i = e.runId;
      try {
        const t = await a.runCellAsync(
          e.code,
          e.stdin || "",
          e.runId || ""
          // propagate correlation ID to WASM so trace spans can be linked end-to-end
        );
        self.postMessage({
          type: "result",
          id: e.id,
          data: t,
          runId: i
        });
      } catch (t) {
        const s = t instanceof Error ? t.message : String(t);
        f.error("runCell_error", { runId: i, error: s }), self.postMessage({
          type: "error",
          id: e.id,
          error: s,
          runId: i
        });
      } finally {
        i = void 0;
      }
      break;
    }
    case "reset": {
      try {
        a.reset(), self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
      } catch (t) {
        const s = t instanceof Error ? t.message : String(t);
        self.postMessage({ type: "error", id: e.id, error: s });
      }
      break;
    }
    case "stop": {
      for (const [t, s] of d)
        s({
          ok: !1,
          error: { message: "Worker stopped", code: "E_STOPPED" }
        }), d.delete(t);
      self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
      break;
    }
    case "setFuelLimit": {
      try {
        a.set_fuel_limit(e.limit), e.id && self.postMessage({ type: "result", id: e.id, data: { ok: !0 } });
      } catch (t) {
        if (e.id) {
          const s = t instanceof Error ? t.message : String(t);
          self.postMessage({ type: "error", id: e.id, error: s });
        }
      }
      break;
    }
    case "inspectGlobals": {
      try {
        const t = a.inspect_globals();
        self.postMessage({ type: "result", id: e.id, data: t });
      } catch (t) {
        const s = t instanceof Error ? t.message : String(t);
        self.postMessage({ type: "error", id: e.id, error: s });
      }
      break;
    }
    case "loadLibrary": {
      try {
        const t = a.load_library(e.source);
        self.postMessage({ type: "result", id: e.id, data: t });
      } catch (t) {
        const s = t instanceof Error ? t.message : String(t);
        self.postMessage({ type: "error", id: e.id, error: s });
      }
      break;
    }
    case "fsCall": {
      const t = M.get(e.action);
      if (!t) {
        self.postMessage({
          type: "error",
          id: e.id,
          error: `Unknown fs action: ${e.action}`
        });
        break;
      }
      try {
        const s = await t(e.params);
        self.postMessage({ type: "result", id: e.id, data: s });
      } catch (s) {
        const o = s instanceof Error ? s.message : String(s);
        self.postMessage({ type: "error", id: e.id, error: o });
      }
      break;
    }
    case "asyncRelayResult": {
      f.debug("asyncRelayResult", {
        id: e.id,
        resultType: typeof e.result
      });
      const t = d.get(e.id);
      t ? (d.delete(e.id), t(e.result)) : f.warn("asyncRelayResult_no_pending_relay", { id: e.id });
      break;
    }
  }
};
