import { i as g, b as D, a as v, c as F, d as S, e as M, f as A, m as L, L as k, E } from "./language-defaults-base.js";
import { supportedLocales as I, fetchT9nStringsBundle as C } from "@arcgis/toolkit/intl";
import { g as h } from "./runtime.js";
import { CompletionItemKind as T, InsertTextFormat as p, InsertTextMode as f } from "vscode-languageserver-types";
import { getDeclaredPixelMembers as j } from "@arcgis/core/applications/Components/arcadeEditorUtils.js";
import "@arcgis/toolkit/type";
/*! All material copyright Esri, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/5.0/esri/copyright.txt for details.
v5.0.0-next.128 */
async function $(e) {
  const { apiVersion: r, bundles: n, hiddenApiItems: i } = e.toEditorProfileDefinition(), t = await P(e.dictionaryVariables);
  return { apiVersion: r, bundles: n, variables: t, hiddenApiItems: i?.map((s) => s.toLowerCase()) };
}
async function P(e, r = T.Variable) {
  return await Promise.all(
    e.map(async (n) => {
      switch (n.type) {
        case "dictionary":
          return await q(n, r);
        case "pixel":
          return await _(n, r);
        // Voxel is equivalent to features in regards to the languageservice.
        // They both have equivalent fields, but some voxel fields are different types (arrays)
        // than what is reported in .fields, so in the sidebar we treat a bit differently.
        // In autocomplete we don't differentiate types, so we can use the same logic as features.
        case "voxel":
        case "feature":
          return await K(n, r);
        default:
          return B(n, r);
      }
    })
  );
}
function B(e, r) {
  const { name: n, type: i } = e, t = e.getDescription();
  return {
    name: n,
    description: t,
    type: i,
    completion: {
      label: n,
      detail: n,
      insertText: n,
      insertTextMode: f.asIs,
      insertTextFormat: p.PlainText,
      kind: r,
      documentation: { kind: "markdown", value: t }
    }
  };
}
async function K(e, r) {
  const n = await e.loadSource(), { name: i } = e, t = e.getDescription(), s = {
    label: i,
    detail: i,
    insertText: i,
    insertTextMode: f.asIs,
    insertTextFormat: p.PlainText,
    kind: r
  }, o = {
    name: i,
    description: t,
    type: "dictionary",
    properties: [],
    completion: s
  };
  if (!n)
    return o;
  const [a, c] = A(n.fields, t, !0);
  return o.properties = a, s.documentation = { kind: "markdown", value: c }, o;
}
async function _(e, r) {
  const n = await e.loadSource(), i = e.toProfileVariableDefinition();
  if (i.type !== "pixel")
    throw new Error("Incorrect definition passed to pixel variable");
  const { name: t } = e, s = e.getDescription(), o = {
    label: t,
    detail: t,
    insertText: t,
    insertTextMode: f.asIs,
    insertTextFormat: p.PlainText,
    kind: r
  }, a = {
    name: t,
    description: s,
    type: "dictionary",
    properties: [],
    completion: o
  };
  if (!n || !i.definition)
    return a;
  const c = await j(n), [d, l] = L(c, s);
  return a.properties = d, o.documentation = { kind: "markdown", value: l }, a;
}
async function q(e, r) {
  const { name: n, dictionaryVariables: i } = e, t = e.getDescription(), s = i.reduce((o, a) => {
    o !== "" && (o += `  
  
`), o += `**${a.name}**  
${a.type}`;
    const c = a.getDescription();
    return c && (o += `  
${c}`), o;
  }, t);
  return {
    name: n,
    description: t,
    type: "dictionary",
    properties: await P(i, T.Field),
    completion: {
      label: n,
      detail: n,
      insertText: n,
      insertTextMode: f.asIs,
      insertTextFormat: p.PlainText,
      kind: r,
      documentation: { kind: "markdown", value: s }
    }
  };
}
async function y(e = "en") {
  const r = x.get(e);
  if (r)
    return r;
  if (!I.has(e))
    return await y("en");
  try {
    const n = await fetch(h(`./assets/arcade-language/profiles/arcade-profiles.t9n.${e}.json`));
    return n.ok ? Q(e, await n.json()) : e === "en" ? null : await y("en");
  } catch {
    return null;
  }
}
const x = /* @__PURE__ */ new Map();
function Q(e, r) {
  const n = /* @__PURE__ */ new Map();
  return r.forEach((i) => {
    n.set(i.id, i);
  }), x.set(e, n), n;
}
async function U(e, r = "en") {
  return (await y(r))?.get(e) ?? null;
}
function z(e) {
  return !!e && typeof e == "object" && "additionalVariables" in e && Array.isArray(e.additionalVariables);
}
function G(e) {
  return e?.map(m);
}
function m(e) {
  switch (e.type) {
    case "dictionary":
      return {
        ...e,
        type: e.type,
        properties: G(e.properties)
      };
    case "array":
      return {
        ...e,
        type: e.type,
        elementType: { type: "number", name: "number" }
      };
    default:
      return { ...e, type: e.type };
  }
}
async function H(e, r = "en") {
  if (!g(e))
    return;
  const n = await U(e.id, r);
  if (!n)
    return;
  const i = {
    bundles: [...n.bundles],
    variables: [],
    hiddenApiItems: e.hiddenApiItems?.map((t) => t.toLowerCase())
  };
  return n.variables.forEach((t) => {
    if (e.disabledVariables?.includes(t.name))
      return;
    const s = e.definitions[t.name];
    switch (t.type) {
      case "dictionary":
        return i.variables.push(
          m({
            ...t,
            type: t.type,
            properties: Array.isArray(s) ? [...s] : t.properties
          })
        );
      case "feature":
        return M(s) ? i.variables.push({ ...t, type: "feature", definition: s }) : void 0;
      case "pixel":
        return S(s) ? i.variables.push({ ...t, type: t.type, definition: s }) : void 0;
      case "voxel":
        return F(s) ? i.variables.push({ ...t, type: t.type, definition: s }) : void 0;
      case "featureSet":
        return v(s) ? i.variables.push({ ...t, type: t.type, definition: s }) : void 0;
      case "featureSetCollection":
        return D(s) ? i.variables.push({ ...t, type: t.type, definition: s }) : void 0;
      default:
        return i.variables.push(m(t));
    }
  }), z(e) && i.variables.push(...e.additionalVariables ?? []), i;
}
const J = [
  "catalog-footprint",
  "catalog",
  "csv",
  "feature",
  "geojson",
  "knowledge-graph-sublayer",
  "oriented-imagery",
  "subtype-group",
  "subtype-sublayer",
  "wfs"
];
function N(e) {
  return !!e && typeof e == "object" && "type" in e && typeof e.type == "string" && J.includes(e.type);
}
const O = {
  filterFsCollectionLayersFromMap: (e) => (
    // only some layers are supported in arcade feature sets, one example: https://devtopia.esri.com/WebGIS/arcgis-web-components/issues/10715
    N(e)
  )
};
class R extends k {
  /**
   * Per-model update chaining to serialize profile updates.
   *
   * Why this is necessary:
   * `setProfileForModel` does multiple async steps (t9n load, predefined profile conversion,
   * profile -> API conversion, model disposal + re-init). If callers invoke it twice quickly,
   * the *earlier* call can complete *after* the later call and overwrite the newer API context,
   * because a new profile could convert faster than an old one (e.g. if the newer one is a simple
   * editor profile but the older one is a complex predefined profile that takes a while to convert).
   *
   * We prevent that race by chaining a promise per model key so updates for the same model run
   * strictly in call order.
   */
  #e = /* @__PURE__ */ new Map();
  constructor() {
    super("arcade", {
      apiPath: "./assets/arcade-language/api",
      apiPrefix: "arcade-api.t9n."
    });
  }
  /**
   * Create an EditorProfile for the given model id using the given definition and locale.
   * The EditorProfile is used by the the Arcade Language service as well by the coding components.
   * The definition can be a pre-defined profile or an editor profile definition.
   * If the locale is not provided then the 'en' locale is used.
   * @param modelId The model id for which to create the context.
   * @param definition The definition to use for the model context.
   * @param locale The locale to use for the model context.
   * @returns The EditorProfile for the model.
   */
  async setProfileForModel(r, n, i = { locale: "en" }) {
    const t = this._getApiKey(r), o = (this.#e.get(t) || Promise.resolve()).then(async () => {
      const c = n, d = g(c) ? await H(c, i.locale) : c, l = await C(
        i.locale,
        h("./assets/editor-profile/t9n"),
        "messages."
      );
      if (!l)
        throw new Error(`Failed to load the language bundle for ${i.locale}`);
      this.disposeForModel(r);
      const w = new E(
        d,
        l,
        i.locale,
        O
      );
      this._modelToProfileMap.set(t, w);
      const b = await $(w);
      this.updateApiContextForModel(r, {
        locale: i.locale,
        profile: b,
        snippets: i.snippets
      });
    }), a = o.finally(() => {
      this.#e.get(t) === a && this.#e.delete(t);
    });
    return this.#e.set(t, a), await o;
  }
}
const u = new R(), te = {
  setProfileForModel: u.setProfileForModel.bind(u),
  getApiLibraryForModel: u.getApiLibraryForModel.bind(u)
};
export {
  te as a,
  u as b
};
