/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { i as h, a as D, b as v, c as F, d as M, e as S, g as L, f as A, m as k, L as E, E as I } from "./language-defaults-base.js";
import { supportedLocales as C, fetchT9nStringsBundle as j } from "@arcgis/toolkit/intl";
import { g as P } from "./runtime.js";
import { CompletionItemKind as w, InsertTextFormat as p, InsertTextMode as f } from "vscode-languageserver-types";
import { getDeclaredPixelMembers as $ } from "@arcgis/core/applications/Components/arcadeEditorUtils.js";
import "@arcgis/toolkit/type";
async function B(e) {
  const { apiVersion: i, bundles: t, hiddenApiItems: s } = e.toEditorProfileDefinition(), o = await T(e.dictionaryVariables);
  return { apiVersion: i, bundles: t, variables: o, hiddenApiItems: s?.map((a) => a.toLowerCase()) };
}
async function T(e, i = w.Variable) {
  return await Promise.all(
    e.map(async (t) => {
      switch (t.type) {
        case "dictionary":
          return await z(t, i);
        case "pixel":
          return await q(t, i);
        // 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 _(t, i);
        default:
          return K(t, i);
      }
    })
  );
}
function K(e, i) {
  const { name: t, type: s } = e, o = e.getDescription(), a = i === w.Field ? L(t, !1) : t;
  return {
    name: t,
    description: o,
    type: s,
    completion: {
      label: t,
      detail: t,
      insertText: a,
      insertTextMode: f.asIs,
      insertTextFormat: p.PlainText,
      kind: i,
      documentation: { kind: "markdown", value: o }
    }
  };
}
async function _(e, i) {
  const t = await e.loadSource(), { name: s } = e, o = e.getDescription(), a = {
    label: s,
    detail: s,
    insertText: s,
    insertTextMode: f.asIs,
    insertTextFormat: p.PlainText,
    kind: i
  }, n = {
    name: s,
    description: o,
    type: "dictionary",
    properties: [],
    completion: a
  };
  if (!t)
    return n;
  const [r, c] = A(t.fields, o, !0);
  return n.properties = r, a.documentation = { kind: "markdown", value: c }, n;
}
async function q(e, i) {
  const t = await e.loadSource(), s = e.toProfileVariableDefinition();
  if (s.type !== "pixel")
    throw new Error("Incorrect definition passed to pixel variable");
  const { name: o } = e, a = e.getDescription(), n = {
    label: o,
    detail: o,
    insertText: o,
    insertTextMode: f.asIs,
    insertTextFormat: p.PlainText,
    kind: i
  }, r = {
    name: o,
    description: a,
    type: "dictionary",
    properties: [],
    completion: n
  };
  if (!t || !s.definition)
    return r;
  const c = await $(t), [d, l] = k(c, a);
  return r.properties = d, n.documentation = { kind: "markdown", value: l }, r;
}
async function z(e, i) {
  const { name: t, dictionaryVariables: s } = e, o = e.getDescription(), a = s.reduce((n, r) => {
    n !== "" && (n += `  
  
`), n += `**${r.name}**  
${r.type}`;
    const c = r.getDescription();
    return c && (n += `  
${c}`), n;
  }, o);
  return {
    name: t,
    description: o,
    type: "dictionary",
    properties: await T(s, w.Field),
    completion: {
      label: t,
      detail: t,
      insertText: t,
      insertTextMode: f.asIs,
      insertTextFormat: p.PlainText,
      kind: i,
      documentation: { kind: "markdown", value: a }
    }
  };
}
async function y(e = "en") {
  const i = b.get(e);
  if (i)
    return i;
  if (!C.has(e))
    return await y("en");
  try {
    const t = await fetch(P(`./assets/arcade-language/profiles/arcade-profiles.t9n.${e}.json`));
    return t.ok ? O(e, await t.json()) : e === "en" ? null : await y("en");
  } catch {
    return null;
  }
}
const b = /* @__PURE__ */ new Map();
function O(e, i) {
  const t = /* @__PURE__ */ new Map();
  return i.forEach((s) => {
    t.set(s.id, s);
  }), b.set(e, t), t;
}
async function Q(e, i = "en") {
  return (await y(i))?.get(e) ?? null;
}
function U(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, i = "en") {
  if (!h(e))
    return;
  const t = await Q(e.id, i);
  if (!t)
    return;
  const s = e.definitions, o = new Map(
    Object.entries(s).map(([n, r]) => [n.toLowerCase(), r])
  ), a = {
    bundles: [...t.bundles],
    variables: [],
    hiddenApiItems: e.hiddenApiItems?.map((n) => n.toLowerCase())
  };
  return t.variables.forEach((n) => {
    if (e.disabledVariables?.includes(n.name))
      return;
    const r = o.get(n.name.toLowerCase());
    switch (n.type) {
      case "dictionary":
        return a.variables.push(
          m({
            ...n,
            type: n.type,
            properties: Array.isArray(r) ? [...r] : n.properties
          })
        );
      case "feature":
        return S(r) ? a.variables.push({ ...n, type: "feature", definition: r }) : void 0;
      case "pixel":
        return M(r) ? a.variables.push({ ...n, type: n.type, definition: r }) : void 0;
      case "voxel":
        return F(r) ? a.variables.push({ ...n, type: n.type, definition: r }) : void 0;
      case "featureSet":
        return v(r) ? a.variables.push({ ...n, type: n.type, definition: r }) : void 0;
      case "featureSetCollection":
        return D(r) ? a.variables.push({ ...n, type: n.type, definition: r }) : void 0;
      default:
        return a.variables.push(m(n));
    }
  }), U(e) && a.variables.push(...e.additionalVariables ?? []), a;
}
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 R = {
  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 W extends E {
  /**
   * 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(i, t, s = { locale: "en" }) {
    const o = this._getApiKey(i), n = (this.#e.get(o) || Promise.resolve()).then(async () => {
      const c = t, d = h(c) ? await H(c, s.locale) : c, l = await j(
        s.locale,
        P("./assets/editor-profile/t9n"),
        "messages."
      );
      if (!l)
        throw new Error(`Failed to load the language bundle for ${s.locale}`);
      this.disposeForModel(i);
      const g = new I(
        d,
        l,
        s.locale,
        R
      );
      this._modelToProfileMap.set(o, g);
      const x = await B(g);
      this.updateApiContextForModel(i, {
        locale: s.locale,
        profile: x,
        snippets: s.snippets
      });
    }), r = n.finally(() => {
      this.#e.get(o) === r && this.#e.delete(o);
    });
    return this.#e.set(o, r), await n;
  }
}
const u = new W(), ne = {
  setProfileForModel: u.setProfileForModel.bind(u),
  getApiLibraryForModel: u.getApiLibraryForModel.bind(u)
};
export {
  ne as a,
  u as b
};
