import { t as g, a as U, b as z, c as L, d as B, e as Q, f as M, n as P, g as T, h as A } from "../chunks/validation-nOPr0mTk.js";
import { l as Ve, i as $e, j as Ne, k as Ue, v as ze } from "../chunks/validation-nOPr0mTk.js";
import { j as J } from "../chunks/index-CuHybtft.js";
import { createContext as Y, useContext as H, useMemo as p, useState as R, useCallback as O, useEffect as j, useRef as _ } from "react";
import { jsx as W } from "react/jsx-runtime";
import { v as F } from "../chunks/validators-CVuWOHYv.js";
const G = [
  "records",
  "changes",
  "drivers",
  "largestNegativeChanges",
  "largestPositiveChanges",
  "largestNegativeDrivers",
  "largestPositiveDrivers"
], X = [
  "records",
  "changes",
  "drivers",
  "largestNegativeChanges",
  "largestPositiveChanges",
  "largestNegativeDrivers",
  "largestPositiveDrivers"
];
function V(e) {
  if (!e)
    return {};
  const t = ne(e.executionResult), n = Z(e, t), r = te(n);
  return {
    ...e,
    ...Object.keys(n).length ? { resultSets: n } : {},
    ...r ? {
      columns: r.columns,
      records: r.records,
      rowCount: r.rowCount
    } : {}
  };
}
function Z(e, t) {
  const n = ee(e.resultSets);
  for (const i of G) {
    if (n[i]) {
      n[i] = $(n[i]);
      continue;
    }
    const u = oe(e[i]);
    if (!u.length)
      continue;
    const s = t.length ? t : ie(u);
    n[i] = {
      records: b(u, s),
      columns: s,
      rowCount: u.length
    };
  }
  const r = re(e.executionResult);
  return r && r.records.length > 0 && !n.records && (n.records = r), n;
}
function ee(e) {
  return Object.fromEntries(
    Object.entries(e || {}).map(([t, n]) => [
      t,
      $(n)
    ])
  );
}
function $(e) {
  var t;
  return {
    ...e,
    records: b(
      e.records || [],
      e.columns || []
    ),
    rowCount: e.rowCount ?? ((t = e.records) == null ? void 0 : t.length) ?? 0
  };
}
function te(e) {
  var t;
  for (const n of X)
    if ((t = e[n]) != null && t.records.length)
      return e[n];
  return Object.values(e).find((n) => n.records.length) || Object.values(e)[0];
}
function re(e) {
  const t = e == null ? void 0 : e.result;
  if (!(!t || t.kind !== "records" && t.kind !== "sql"))
    return {
      records: b(t.records, t.columns),
      columns: t.columns,
      rowCount: t.rowCount ?? t.records.length
    };
}
function ne(e) {
  const t = e == null ? void 0 : e.result;
  return !t || t.kind !== "records" && t.kind !== "sql" ? [] : t.columns;
}
function oe(e) {
  return Array.isArray(e) ? e.filter(
    (t) => !!(t && typeof t == "object" && !Array.isArray(t))
  ) : [];
}
function b(e, t) {
  return t.length ? e.map((n) => {
    const r = {};
    return t.forEach((i, u) => {
      const s = ue(n, {
        name: i.key,
        label: i.label,
        fallbackNames: [i.name, Object.keys(n)[u]]
      });
      s !== void 0 && (r[i.key] = s);
    }), Object.keys(r).length ? r : n;
  }) : e;
}
function ie(e) {
  return Array.from(
    new Set(e.flatMap((n) => Object.keys(n)))
  ).map((n) => ({
    key: n,
    name: n,
    label: n
  }));
}
function ue(e, t) {
  const n = [
    t.name,
    t.label,
    ...t.fallbackNames || []
  ].filter((r) => !!r);
  for (const r of n)
    if (Object.prototype.hasOwnProperty.call(e, r))
      return e[r];
}
function be(e) {
  return e;
}
function Ke(e) {
  return e;
}
const xe = {
  filter(e) {
    return {
      ...e,
      kind: "filter"
    };
  },
  control(e) {
    return {
      ...e,
      kind: "control"
    };
  },
  sqlParam(e) {
    return {
      ...e,
      kind: "control",
      role: "sqlParam"
    };
  },
  metric(e) {
    return {
      ...e,
      queryKind: "metric"
    };
  },
  analysis(e) {
    return {
      ...e,
      queryKind: "analysis"
    };
  },
  records(e) {
    return {
      ...e,
      queryKind: "records"
    };
  },
  inputOptions(e) {
    return {
      ...e,
      queryKind: "inputOptions"
    };
  },
  sql(e) {
    return {
      ...e,
      queryKind: "sql"
    };
  }
};
function se() {
  return {
    executeAnalysis: (e, t, n) => h(
      e,
      t,
      n ?? {}
    ).then(V),
    executeMetric: (e, t) => h(e, t),
    executeRecords: (e, t) => h(e, t),
    executeInputOptions: (e, t) => h(e, t),
    executeSql: (e, t) => h(e, t)
  };
}
async function h(e, t, n) {
  if (!t.token)
    throw new Error("SemaphorDataAppProvider needs a token to execute queries.");
  const r = await fetch(le(t), {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${t.token}`
    },
    body: JSON.stringify({
      intent: e,
      activeInputs: t.activeInputs,
      ...n ? { analysisOptions: n } : {},
      resultShape: e.kind
    })
  }), i = await ae(r);
  if (!r.ok || i.error)
    throw new Error(
      i.error || `Semaphor Data App execution failed with status ${r.status}.`
    );
  return i;
}
async function ae(e) {
  const t = await e.text().catch(() => "");
  if (!t.trim())
    return e.ok ? {
      error: "Semaphor Data App execution returned an empty response."
    } : {};
  try {
    return JSON.parse(t);
  } catch {
    return e.ok ? {
      error: "Semaphor Data App execution returned invalid JSON.",
      details: t
    } : {
      error: ce(e, t),
      details: t
    };
  }
}
function ce(e, t) {
  const n = e.statusText ? ` ${e.statusText}` : "", r = t.replace(/\s+/g, " ").trim();
  return r ? `Semaphor Data App execution failed with status ${e.status}${n}: ${r.slice(0, 240)}` : `Semaphor Data App execution failed with status ${e.status}${n}.`;
}
function le(e) {
  const t = de(e).replace(/\/+$/, "");
  return t ? t.endsWith("/api") ? `${t}/v1/data-app/execute` : `${t}/api/v1/data-app/execute` : "/api/v1/data-app/execute";
}
function de(e) {
  if (e.apiBaseUrl)
    return e.apiBaseUrl;
  if (!e.token)
    return "";
  try {
    return J(e.token).apiServiceUrl || "";
  } catch {
    return "";
  }
}
const N = Y({});
function fe() {
  if (!(typeof window > "u"))
    return window.__SEMAPHOR_DATA_APP_RUNTIME__;
}
function pe() {
  return H(N);
}
function we({
  token: e,
  apiBaseUrl: t,
  executor: n,
  children: r
}) {
  var o;
  const i = fe(), u = ((o = i == null ? void 0 : i.authToken) == null ? void 0 : o.accessToken) || e, s = (i == null ? void 0 : i.dataApiBaseUrl) || (i == null ? void 0 : i.apiBaseUrl) || t, d = p(() => se(), []), a = n || d, c = p(
    () => ({
      token: u,
      apiBaseUrl: s,
      executor: a
    }),
    [s, a, u]
  );
  return /* @__PURE__ */ W(N.Provider, { value: c, children: r });
}
const k = { value: null }, I = {}, me = { records: [] }, E = { options: [] }, he = { records: [] };
function ve(e) {
  const t = g(e.inputs), n = B(e);
  try {
    const r = Q(e), i = v(r);
    return i ? {
      error: i,
      activeInputs: t,
      analysisOptions: n,
      queryKey: f(void 0, t, i, n),
      idleData: I
    } : {
      intent: r,
      error: null,
      activeInputs: t,
      analysisOptions: n,
      queryKey: f(r, t, void 0, n),
      idleData: I
    };
  } catch (r) {
    const i = m(r);
    return {
      error: i,
      activeInputs: t,
      analysisOptions: n,
      queryKey: f(void 0, t, i, n),
      idleData: I
    };
  }
}
function ye(e) {
  const t = g(e.inputs);
  try {
    const n = M(e), r = v(n);
    return r ? {
      error: r,
      activeInputs: t,
      queryKey: f(void 0, t, r),
      idleData: k
    } : {
      intent: n,
      error: null,
      activeInputs: t,
      queryKey: f(n, t),
      idleData: k
    };
  } catch (n) {
    const r = m(n);
    return {
      error: r,
      activeInputs: t,
      queryKey: f(void 0, t, r),
      idleData: k
    };
  }
}
function qe(e) {
  const t = g(e.inputs), n = me;
  try {
    const r = L(e), i = v(r);
    return i ? {
      error: i,
      activeInputs: t,
      queryKey: f(void 0, t, i),
      idleData: n
    } : {
      intent: r,
      error: null,
      activeInputs: t,
      queryKey: f(r, t),
      idleData: n
    };
  } catch (r) {
    const i = m(r);
    return {
      error: i,
      activeInputs: t,
      queryKey: f(void 0, t, i),
      idleData: n
    };
  }
}
function Se(e) {
  try {
    const t = z(e), n = v(t);
    return n ? {
      error: n,
      queryKey: f(void 0, void 0, n),
      idleData: E
    } : {
      intent: t,
      error: null,
      queryKey: f(t),
      idleData: E
    };
  } catch (t) {
    const n = m(t);
    return {
      error: n,
      queryKey: f(void 0, void 0, n),
      idleData: E
    };
  }
}
function Ae(e) {
  const t = g(e.inputs), n = he;
  try {
    const r = U(e), i = v(r);
    return i ? {
      error: i,
      activeInputs: t,
      queryKey: f(void 0, t, i),
      idleData: n
    } : {
      intent: r,
      error: null,
      activeInputs: t,
      queryKey: f(r, t),
      idleData: n
    };
  } catch (r) {
    const i = m(r);
    return {
      error: i,
      activeInputs: t,
      queryKey: f(void 0, t, i),
      idleData: n
    };
  }
}
function m(e) {
  return e instanceof Error ? e : new Error(String(e));
}
function v(e) {
  const t = F(e);
  if (t.ok)
    return null;
  const n = t.errors.map(
    (r) => r.path ? `${r.code} at ${r.path}: ${r.message}` : `${r.code}: ${r.message}`
  ).join("; ");
  return new Error(`Invalid Semaphor analytics intent. ${n}`);
}
function f(e, t, n, r) {
  return JSON.stringify({
    intent: e,
    activeInputs: t,
    analysisOptions: r,
    error: n == null ? void 0 : n.message
  });
}
function Ce(e) {
  const [t, n] = R(e.defaultValue), r = Object.prototype.hasOwnProperty.call(e, "value"), i = r ? e.value : t, u = p(
    () => P(e.options),
    [e.options]
  ), s = O(
    (a) => {
      var o;
      const c = a;
      (o = e.onValueChange) == null || o.call(e, c), r || n(c);
    },
    [r, e]
  ), d = O(() => s(void 0), [s]);
  return p(() => {
    const a = T(e);
    return {
      id: e.id,
      kind: e.kind,
      label: e.label,
      field: a.field,
      operator: a.operator,
      controlRole: e.kind === "control" ? e.role : void 0,
      value: i,
      options: u,
      isActive: A(i),
      setValue: s,
      clear: d,
      toAnalyticsInput: () => ({
        inputId: a.inputId,
        field: a.field,
        kind: e.kind,
        label: e.label,
        value: i,
        isActive: A(i),
        operator: a.operator,
        controlRole: e.kind === "control" ? e.role : void 0
      })
    };
  }, [d, u, s, e, i]);
}
function _e(e) {
  const [t, n] = R(() => ke(e));
  return j(() => {
    n((r) => {
      let i = r;
      for (const u of e)
        !Object.prototype.hasOwnProperty.call(i, u.id) && u.defaultValue !== void 0 && (i = { ...i, [u.id]: u.defaultValue });
      return i;
    });
  }, [e]), p(
    () => e.map((r) => {
      const i = Object.prototype.hasOwnProperty.call(
        r,
        "value"
      ), u = i ? r.value : t[r.id], s = P(r.options), d = (o) => {
        var l;
        (l = r.onValueChange) == null || l.call(r, o), i || n((y) => ({
          ...y,
          [r.id]: o
        }));
      }, a = () => d(void 0), c = T(r);
      return {
        id: r.id,
        kind: r.kind,
        label: r.label,
        field: c.field,
        operator: c.operator,
        controlRole: r.kind === "control" ? r.role : void 0,
        value: u,
        options: s,
        isActive: A(u),
        setValue: d,
        clear: a,
        toAnalyticsInput: () => ({
          inputId: c.inputId,
          field: c.field,
          kind: r.kind,
          label: r.label,
          value: u,
          isActive: A(u),
          operator: c.operator,
          controlRole: r.kind === "control" ? r.role : void 0
        })
      };
    }),
    [e, t]
  );
}
function Pe(e, t = {}) {
  const n = p(
    () => t.inputs ? {
      ...e,
      inputs: t.inputs
    } : e,
    [t.inputs, e]
  ), r = p(() => {
    switch (n.queryKind) {
      case "metric":
        return {
          queryKind: n.queryKind,
          request: ye(n)
        };
      case "analysis":
        return {
          queryKind: n.queryKind,
          request: ve(n)
        };
      case "records":
        return {
          queryKind: n.queryKind,
          request: qe(n)
        };
      case "inputOptions":
        return {
          queryKind: n.queryKind,
          request: Se(n)
        };
      case "sql":
        return {
          queryKind: n.queryKind,
          request: Ae(n)
        };
      default:
        return D(n);
    }
  }, [n]), i = O(
    (o) => {
      var y, q, K, x, w, S, C;
      const l = r.request;
      if (l.intent)
        switch (r.queryKind) {
          case "metric":
            return (y = o.executor) == null ? void 0 : y.executeMetric(
              l.intent,
              o
            );
          case "analysis":
            return (K = (q = o.executor) == null ? void 0 : q.executeAnalysis) == null ? void 0 : K.call(
              q,
              l.intent,
              o,
              l.analysisOptions
            );
          case "records":
            return (x = o.executor) == null ? void 0 : x.executeRecords(
              l.intent,
              o
            );
          case "inputOptions":
            return (w = o.executor) == null ? void 0 : w.executeInputOptions(
              l.intent,
              o
            );
          case "sql":
            return (C = (S = o.executor) == null ? void 0 : S.executeSql) == null ? void 0 : C.call(
              S,
              l.intent,
              o
            );
          default:
            return D(r);
        }
    },
    [r]
  ), u = ge(
    r.request.queryKey,
    i,
    r.request.idleData,
    r.request.activeInputs
  ), s = r.request.error ? r.request.idleData : u.data, d = r.request.error ? "error" : u.status, a = !r.request.error && u.status === "loading", c = r.request.error || u.error;
  switch (r.queryKind) {
    case "metric": {
      const o = s;
      return {
        id: n.id,
        intent: r.request.intent,
        value: (o == null ? void 0 : o.value) ?? null,
        metrics: o == null ? void 0 : o.metrics,
        comparisonValue: o == null ? void 0 : o.comparisonValue,
        delta: o == null ? void 0 : o.delta,
        deltaPercent: o == null ? void 0 : o.deltaPercent,
        records: o == null ? void 0 : o.records,
        executionResult: o == null ? void 0 : o.executionResult,
        status: d,
        isLoading: a,
        error: c
      };
    }
    case "analysis": {
      const o = V(s);
      return {
        id: n.id,
        intent: r.request.intent,
        ...o || {},
        status: d,
        isLoading: a,
        error: c
      };
    }
    case "records": {
      const o = s;
      return {
        id: n.id,
        intent: r.request.intent,
        records: (o == null ? void 0 : o.records) || [],
        columns: o == null ? void 0 : o.columns,
        rowCount: o == null ? void 0 : o.rowCount,
        pagination: o == null ? void 0 : o.pagination,
        executionResult: o == null ? void 0 : o.executionResult,
        status: d,
        isLoading: a,
        error: c
      };
    }
    case "inputOptions": {
      const o = s;
      return {
        id: n.id,
        intent: r.request.intent,
        options: (o == null ? void 0 : o.options) || [],
        executionResult: o == null ? void 0 : o.executionResult,
        status: d,
        isLoading: a,
        error: c
      };
    }
    case "sql": {
      const o = s;
      return {
        id: n.id,
        intent: r.request.intent,
        records: (o == null ? void 0 : o.records) || [],
        columns: o == null ? void 0 : o.columns,
        rowCount: o == null ? void 0 : o.rowCount,
        pagination: o == null ? void 0 : o.pagination,
        output: o == null ? void 0 : o.output,
        rowLimitExceeded: o == null ? void 0 : o.rowLimitExceeded,
        executionResult: o == null ? void 0 : o.executionResult,
        status: d,
        isLoading: a,
        error: c
      };
    }
    default:
      return D(r);
  }
}
function ge(e, t, n, r) {
  const i = pe(), u = _(t), s = _(r), [d, a] = R({
    status: "idle",
    data: n,
    error: null
  });
  return u.current = t, s.current = r, j(() => {
    let c;
    try {
      c = u.current({
        ...i,
        activeInputs: s.current
      });
    } catch (l) {
      a({
        status: "error",
        data: n,
        error: m(l)
      });
      return;
    }
    if (!c) {
      a({ status: "idle", data: n, error: null });
      return;
    }
    let o = !1;
    return a((l) => ({
      status: "loading",
      data: l.data,
      error: null
    })), c.then((l) => {
      o || a({ status: "success", data: l, error: null });
    }).catch((l) => {
      o || a({
        status: "error",
        data: n,
        error: m(l)
      });
    }), () => {
      o = !0;
    };
  }, [n, e, i]), d;
}
function ke(e) {
  return Object.fromEntries(
    e.filter((t) => t.defaultValue !== void 0).map((t) => [t.id, t.defaultValue])
  );
}
function D(e) {
  throw new Error(`Unsupported Semaphor query kind: ${JSON.stringify(e)}`);
}
export {
  N as SemaphorDataAppContext,
  we as SemaphorDataAppProvider,
  se as createSemaphorQueryExecutor,
  be as defineSemaphorDataApp,
  Ke as defineSemaphorInput,
  A as hasSemaphorInputValue,
  V as normalizeSemaphorAnalysisPayload,
  Ve as normalizeSemaphorAnalysisQueryOptions,
  P as normalizeSemaphorInputOptions,
  fe as readWindowRuntime,
  xe as semaphor,
  g as toSemaphorActiveInputSnapshots,
  Q as toSemaphorAnalysisIntent,
  B as toSemaphorAnalysisQueryOptions,
  $e as toSemaphorInputBinding,
  Ne as toSemaphorInputBindings,
  z as toSemaphorInputOptionsIntent,
  Ue as toSemaphorInputSnapshots,
  T as toSemaphorInputSpec,
  M as toSemaphorMetricIntent,
  L as toSemaphorRecordsIntent,
  U as toSemaphorSqlIntent,
  pe as useSemaphorDataAppRuntime,
  Ce as useSemaphorInput,
  _e as useSemaphorInputs,
  Pe as useSemaphorQuery,
  ze as validateSemaphorDataAppQuerySpecs
};
