import { D as B, a as be } from "../chunks/contracts-CoCOpd_i.js";
import { s as Ie, a as E, p as ye } from "../chunks/source-identity-Dj3dryN9.js";
import { v as ae, d as _e, n as we } from "../chunks/validators-CVuWOHYv.js";
import { b as ve } from "../chunks/catalog-field-grounding-DoEBOXQd.js";
function _(e) {
  return e && typeof e == "object" ? e : null;
}
function C(e) {
  return typeof e == "string" ? e : null;
}
function Se(e) {
  var t, n, r;
  return !!(e && typeof e == "object") && (((t = _(e)) == null ? void 0 : t.kind) === "semantic" || ((n = _(e)) == null ? void 0 : n.kind) === "physical" || ((r = _(e)) == null ? void 0 : r.kind) === "sql");
}
function z(e) {
  return Se(e) ? e.kind === "semantic" ? !!(e.domainId && e.datasetName) : e.kind === "physical" ? !!(e.connectionId && e.tableName) : !1 : !1;
}
function wt(e) {
  return Ie(e);
}
function ie(e, t) {
  return E(e, t);
}
function Ce(e, t) {
  return ye(e, t);
}
function P(e) {
  const t = [];
  for (const n of e) {
    const r = t.findIndex(
      (o) => ie(o, n)
    );
    r === -1 ? t.push(n) : t[r] = Ce(
      t[r],
      n
    );
  }
  return t;
}
function vt(e) {
  return P(e)[0];
}
function L(e, t) {
  return e.kind !== "semantic" || e.connectionId || (t == null ? void 0 : t.kind) !== "semantic" || !E(e, t) || !t.connectionId ? e : { ...e, connectionId: t.connectionId };
}
function j(e) {
  return z(e) ? e : void 0;
}
function ne(e, t) {
  if (!(e.kind !== "semantic" || e.connectionId))
    return t.find(
      (n) => (n == null ? void 0 : n.kind) === "semantic" && E(e, n) && !!n.connectionId
    );
}
function S(e, t) {
  const n = j(e == null ? void 0 : e.source);
  return n ? L(n, t) : void 0;
}
function ke({
  explicitSource: e,
  field: t,
  defaultSource: n,
  fallbackSources: r
}) {
  const o = [n, ...r || []], a = j(e), i = a ? L(
    a,
    ne(a, o)
  ) : void 0;
  if (i)
    return i;
  if (e !== void 0)
    return;
  const d = S(t, n), s = d ? L(
    d,
    ne(d, o)
  ) : void 0;
  if (s)
    return s;
  if ((t == null ? void 0 : t.source) === void 0)
    return j(n);
}
function St(e, t) {
  if (!(e != null && e.name) || !(t != null && t.name) || e.name !== t.name)
    return !1;
  const n = S(e), r = S(t);
  return !n || !r ? !0 : ie(n, r);
}
function k(e) {
  var t;
  return C((t = _(e)) == null ? void 0 : t.kind);
}
function oe(e) {
  var t, n;
  return k(e) !== "semantic" ? null : ((n = C((t = _(e)) == null ? void 0 : t.domainId)) == null ? void 0 : n.trim()) || null;
}
function xe(e) {
  var t;
  return k(e) !== "semantic" ? null : C((t = _(e)) == null ? void 0 : t.datasetName);
}
function De(e) {
  var t;
  return k(e) !== "semantic" ? null : C((t = _(e)) == null ? void 0 : t.datasetId);
}
function Ae(e) {
  var t;
  return k(e) !== "physical" ? null : C((t = _(e)) == null ? void 0 : t.connectionId);
}
function Fe(e) {
  var t;
  return k(e) !== "physical" ? null : C((t = _(e)) == null ? void 0 : t.tableName);
}
function Te(e) {
  var t;
  return k(e) !== "physical" ? "" : C((t = _(e)) == null ? void 0 : t.databaseName) || "";
}
function $e(e) {
  var t;
  return k(e) !== "physical" ? "" : C((t = _(e)) == null ? void 0 : t.schemaName) || "";
}
function Me(e) {
  if (e.analyticsIntent && typeof e.analyticsIntent == "object" && "source" in e.analyticsIntent)
    return e.analyticsIntent.source;
}
function Ne({
  datasets: e,
  requireAtLeastOne: t
}) {
  if (t && e.length < 1)
    return { ok: !1, issue: "invalid_dataset_count" };
  if (e.length <= 1)
    return { ok: !0 };
  const n = e.map(oe), r = new Set(n.filter(Boolean));
  return n.some((o) => !o) || r.size !== 1 ? { ok: !1, issue: "invalid_multi_dataset_scope" } : { ok: !0 };
}
function H(e, t) {
  if (!t)
    return !1;
  if (t.kind === "semantic") {
    const n = De(e);
    return oe(e) === t.domainId ? n && t.datasetId ? n === t.datasetId : xe(e) === t.datasetName : !1;
  }
  return t.kind === "physical" ? Ae(e) === t.connectionId && Fe(e) === t.tableName && Te(e) === (t.databaseName || "") && $e(e) === (t.schemaName || "") : !1;
}
function Ct(e, t) {
  return e.find(
    (n) => H(n, t)
  );
}
function p(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function M(e) {
  const t = /* @__PURE__ */ new Set();
  for (const n of e) {
    if (t.has(n))
      return n;
    t.add(n);
  }
  return null;
}
function se({
  card: e,
  datasets: t,
  errors: n
}) {
  if (e.type === "text")
    return;
  const r = Me(e);
  if (!r) {
    if (t.length <= 1)
      return;
    n.push(
      p(
        "missing_card_analytics_source",
        "Multi-dataset dashboard cards must include analytics intent with a source so the materializer can choose the correct dataset.",
        e.id
      )
    );
    return;
  }
  t.some((o) => H(o, r)) || n.push(
    p(
      "invalid_card_analytics_source",
      "Dashboard cards with an explicit analytics source must use one of the selected datasets.",
      e.id
    )
  );
}
function N(e) {
  return e.map((t) => t == null ? void 0 : t.source).filter((t) => !!t);
}
function q(e) {
  return Array.isArray(e) ? e.filter(
    (t) => !!(t && typeof t == "object")
  ) : [];
}
function re(e) {
  return Array.isArray(e) ? e.filter(
    (t) => !!(t && typeof t == "object")
  ) : [];
}
function Be(e) {
  var n;
  if (!e)
    return [];
  const t = [e.source];
  return e.kind === "metric" ? t.push(
    ...N([
      ...q(e.metrics),
      e.primaryMetric,
      e.dateField,
      ...q(e.dimensions),
      ...re(e.filters).map((r) => r.field)
    ])
  ) : e.kind === "records" ? t.push(
    ...N([
      ...q(e.fields),
      e.dateField,
      (n = e.orderBy) == null ? void 0 : n.field,
      ...re(e.filters).map((r) => r.field)
    ])
  ) : e.kind === "inputOptions" ? t.push(...N([e.field])) : e.kind === "sql" && t.push(...N(e.fields || [])), t;
}
function de({
  card: e,
  datasets: t,
  errors: n
}) {
  if (e.type !== "text") {
    for (const r of Be(e.analyticsIntent))
      if (r && !t.some(
        (o) => H(o, r)
      )) {
        n.push(
          p(
            "invalid_card_query_source",
            "Dashboard card query field references must use one of the selected datasets.",
            e.id
          )
        );
        return;
      }
  }
}
function ce({
  card: e,
  errors: t
}) {
  if (e.type === "text" || !e.analyticsIntent)
    return;
  const n = ae(e.analyticsIntent);
  if (!n.ok)
    for (const r of n.errors)
      t.push(
        p(
          r.code,
          r.path ? `${r.path}: ${r.message}` : r.message,
          e.id
        )
      );
}
function le({
  datasets: e,
  errors: t,
  requireAtLeastOne: n
}) {
  const r = Ne({
    datasets: e,
    requireAtLeastOne: n
  });
  if (!r.ok) {
    if (r.issue === "invalid_dataset_count") {
      t.push(
        p(
          "invalid_dataset_count",
          "Dashboard authoring requires at least one selected dataset."
        )
      );
      return;
    }
    t.push(
      p(
        "invalid_multi_dataset_scope",
        "Multi-dataset dashboard authoring is limited to semantic datasets from one domain."
      )
    );
  }
}
function Pe(e) {
  var f, g;
  const t = [];
  if (!e || typeof e != "object")
    return {
      ok: !1,
      errors: [
        p(
          "invalid_plan",
          "Dashboard plan must be a structured object."
        )
      ],
      warnings: []
    };
  const n = e, r = [...n.warnings || []];
  n.version !== 1 && t.push(p("invalid_version", "Dashboard plan version must be 1.")), (f = n.title) != null && f.trim() || t.push(p("missing_title", "Dashboard plan needs a title."));
  const o = Array.isArray(n.datasets) ? n.datasets : [], a = Array.isArray(n.sheets) ? n.sheets : [];
  le({ datasets: o, errors: t, requireAtLeastOne: !0 }), a.length !== 1 && t.push(
    p(
      "invalid_sheet_count",
      "MVP dashboard authoring creates exactly one dashboard sheet."
    )
  );
  const i = a[0];
  i && i.kind !== "dashboard" && t.push(
    p("invalid_sheet_kind", 'Generated sheet must use kind "dashboard".')
  );
  const d = (i == null ? void 0 : i.cards) || [];
  d.length > B && t.push(
    p(
      "too_many_cards",
      `Generated dashboards can contain at most ${B} cards.`
    )
  );
  const s = M(d.map((l) => l.id));
  s && t.push(
    p("duplicate_card_id", `Duplicate generated card id: ${s}.`)
  );
  const u = M(d.map((l) => l.frameId));
  u && t.push(
    p(
      "duplicate_frame_id",
      `Duplicate generated frame id: ${u}.`
    )
  );
  for (const l of d)
    (g = l.title) != null && g.trim() || t.push(p("missing_card_title", "Card title is required.", l.id)), l.type === "custom" && t.push(
      p(
        "custom_visual_out_of_scope",
        "Whole-dashboard authoring supports built-in visual types only.",
        l.id
      )
    ), l.type !== "text" && !l.analyticsIntent && r.push(
      p(
        "missing_analytics_intent",
        "Non-text card has no analytics intent and may be skipped by the app layer.",
        l.id
      )
    ), se({ card: l, datasets: o, errors: t }), ce({ card: l, errors: t }), de({ card: l, datasets: o, errors: t });
  const h = Array.isArray(n.filterInputs) ? n.filterInputs : [], I = h.map((l) => l.id), w = M(I);
  w && t.push(
    p(
      "duplicate_input_id",
      `Duplicate dashboard input id: ${w}.`
    )
  );
  const v = h.map((l) => l.variableName).filter(Boolean) || [], y = M(v);
  y && t.push(
    p(
      "duplicate_input_variable",
      `Duplicate dashboard input variable name: ${y}.`
    )
  );
  const c = Array.isArray(n.calculatedFields) ? n.calculatedFields : [];
  for (const l of c)
    l.scope === "domain" && l.reuseOnly !== !0 && t.push(
      p(
        "domain_calculated_field_create_out_of_scope",
        `Creating domain calculated field "${l.name}" is outside MVP.`
      )
    );
  return { ok: t.length === 0, errors: t, warnings: r };
}
function ze(e) {
  var i;
  const t = [];
  if (!e || typeof e != "object")
    return {
      ok: !1,
      errors: [
        p(
          "invalid_change_plan",
          "Dashboard change plan must be a structured object."
        )
      ],
      warnings: []
    };
  const n = e, r = [...n.warnings || []];
  n.version !== 1 && t.push(
    p("invalid_version", "Dashboard change plan version must be 1.")
  ), (i = n.dashboardId) != null && i.trim() || t.push(
    p("missing_dashboard_id", "Dashboard change plan needs a dashboard id.")
  );
  const o = Array.isArray(n.datasets) ? n.datasets : [], a = Array.isArray(n.operations) ? n.operations : [];
  le({ datasets: o, errors: t, requireAtLeastOne: !1 });
  for (const d of a) {
    if (d.kind === "unsupported") {
      r.push(
        p("unsupported_operation", d.reason || d.requestedAction)
      );
      continue;
    }
    d.kind === "addCard" && d.card.type === "custom" && t.push(
      p(
        "custom_visual_out_of_scope",
        "Whole-dashboard authoring supports built-in visual types only.",
        d.card.id
      )
    ), d.kind === "addCard" && (se({
      card: d.card,
      datasets: o,
      errors: t
    }), ce({
      card: d.card,
      errors: t
    }), de({
      card: d.card,
      datasets: o,
      errors: t
    })), d.kind === "addCalculatedField" && d.field.scope === "domain" && d.field.reuseOnly !== !0 && t.push(
      p(
        "domain_calculated_field_create_out_of_scope",
        `Creating domain calculated field "${d.field.name}" is outside MVP.`
      )
    );
  }
  return { ok: t.length === 0, errors: t, warnings: r };
}
const Ve = {
  lg: 48,
  md: 36,
  sm: 24,
  xs: 12,
  xxs: 6
};
function qe(e, t) {
  let n = 0, r = 0, o = 0;
  return e.map((a) => {
    const i = Math.min(a.w, t);
    n > 0 && n + i > t && (n = 0, r += o, o = 0);
    const d = {
      i: a.frameId,
      x: n,
      y: r,
      w: i,
      h: a.h,
      minW: Math.min(a.minW, t),
      minH: a.minH,
      static: !1
    };
    return n += i, o = Math.max(o, a.h), d;
  });
}
function Re(e) {
  const t = [...e].sort((s, u) => s.priority - u.priority), n = t.filter((s) => s.role === "kpi"), r = t.filter((s) => s.role === "chart"), o = t.filter((s) => s.role === "table"), a = t.filter((s) => s.role === "text"), i = a.slice(0, 1), d = a.slice(i.length);
  return { kpis: n, introText: i, charts: r, tables: o, supportingText: d };
}
function Oe(e, t, n) {
  return t === "xxs" || t === "xs" ? n : t === "sm" ? Math.min(12, n) : t === "md" ? e <= 1 || e === 2 ? 18 : 12 : e <= 1 || e === 2 ? 24 : e === 3 ? 16 : 12;
}
function Le(e, t, n, r) {
  return n === "xxs" || n === "xs" || n === "sm" || n === "md" || t === 1 || t % 2 === 1 && e === 0 ? r : r / 2;
}
function je(e) {
  const { item: t, band: n, index: r, bandCount: o, breakpoint: a, columns: i } = e;
  return n === "kpi" ? {
    ...t,
    band: n,
    w: Oe(o, a, i),
    h: 15,
    minW: Math.min(6, i),
    minH: 12
  } : n === "table" ? {
    ...t,
    band: n,
    w: i,
    h: a === "xxs" || a === "xs" ? 34 : 38,
    minW: Math.min(12, i),
    minH: 18
  } : n === "introText" ? {
    ...t,
    band: n,
    w: i,
    h: a === "xxs" || a === "xs" ? 12 : 10,
    minW: Math.min(12, i),
    minH: 8
  } : n === "supportingText" ? {
    ...t,
    band: n,
    w: a === "lg" ? i / 2 : i,
    h: a === "xxs" || a === "xs" ? 12 : 10,
    minW: Math.min(12, i),
    minH: 8
  } : {
    ...t,
    band: n,
    w: Le(r, o, a, i),
    h: a === "xxs" || a === "xs" ? 28 : 30,
    minW: Math.min(12, i),
    minH: 16
  };
}
function A(e, t, n, r) {
  return e.map(
    (o, a) => je({
      item: o,
      band: t,
      index: a,
      bandCount: e.length,
      breakpoint: n,
      columns: r
    })
  );
}
function K(e) {
  const t = Re(e);
  return Object.fromEntries(
    be.map((n) => {
      const r = Ve[n], o = [
        ...A(t.introText, "introText", n, r),
        ...A(t.kpis, "kpi", n, r),
        ...A(t.charts, "chart", n, r),
        ...A(t.tables, "table", n, r),
        ...A(t.supportingText, "supportingText", n, r)
      ];
      return [n, qe(o, r)];
    })
  );
}
function We(e) {
  const t = ve(e);
  return t === "datetime" ? "date" : t === "unknown" ? "string" : t;
}
function Ee(e) {
  return !!(e && typeof e == "object" && !Array.isArray(e));
}
function He(e) {
  return Ee(e) && typeof e.filterId == "string" && typeof e.operation == "string" && Array.isArray(e.values);
}
function Ke(e) {
  return e.filter(
    (t) => typeof t == "string" || typeof t == "number"
  );
}
function Ge(e) {
  return e.filter(
    (t) => t instanceof Date || typeof t == "string"
  );
}
function G(e, t) {
  if (t === void 0)
    return;
  const n = We(e.dataType), r = e.operation || "in";
  if (He(t))
    return {
      ...t,
      filterId: e.id,
      name: t.name || e.column,
      valueType: n,
      dataType: e.dataType,
      fieldMeta: e.fieldMeta,
      semanticContext: e.semanticContext
    };
  if (r === "is null" || r === "is not null")
    return {
      filterId: e.id,
      name: e.column,
      operation: r,
      valueType: n,
      values: [],
      dataType: e.dataType,
      fieldMeta: e.fieldMeta,
      semanticContext: e.semanticContext
    };
  const o = Array.isArray(t) ? t : [t], a = n === "date" ? Ge(o) : Ke(o);
  if (a.length !== 0 && !((r === "between" || r === "not between") && a.length < 2))
    return {
      filterId: e.id,
      name: e.column,
      operation: r,
      valueType: n,
      values: a,
      dataType: e.dataType,
      fieldMeta: e.fieldMeta,
      semanticContext: e.semanticContext
    };
}
function ue(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function Ue(e, t, n) {
  const r = (t || []).filter(
    (o) => o.scope === "card" && o.targetCardId === n
  ).map((o) => o.field).filter(Boolean);
  return r.length === 0 ? e : {
    ...e,
    calculatedFields: [
      ...e.calculatedFields || [],
      ...r
    ]
  };
}
function W(e, t) {
  return Array.from(
    new Set(
      (e || []).map((n) => t.get(n)).filter((n) => !!n)
    )
  );
}
function Je(e, t) {
  if ((e == null ? void 0 : e.kind) !== "cards")
    return e;
  const n = W(e.cardIds, t);
  return n.length > 0 ? { ...e, cardIds: n } : null;
}
function Qe(e, t) {
  return !e.applyToCardIds && !e.excludeCardIds ? e : {
    ...e,
    ...e.applyToCardIds ? {
      applyToCardIds: W(
        e.applyToCardIds,
        t
      )
    } : {},
    ...e.excludeCardIds ? {
      excludeCardIds: W(
        e.excludeCardIds,
        t
      )
    } : {}
  };
}
function Xe(e, t) {
  const n = {}, r = [];
  return {
    inputs: (e.filterInputs || []).flatMap(
      (a, i) => {
        const d = Je(a.scope, t);
        if (d === null)
          return r.push(
            ue(
              "filter_input_scope_empty",
              `Filter input "${a.label}" was skipped because all scoped cards were skipped during query validation.`
            )
          ), [];
        const s = G(
          a.filter,
          a.defaultValue
        );
        return s && (n.shared ?? (n.shared = {}), n.shared[a.id] = {
          status: "set",
          value: {
            kind: "filter",
            filterValue: s
          }
        }), [
          {
            id: a.id,
            kind: "filter",
            label: a.label,
            variableName: a.variableName,
            scope: d || { kind: "allSheets", sheetKinds: ["dashboard"] },
            runtimeScope: "shared",
            presentation: {
              placement: "toolbar",
              order: i
            },
            exports: ["label", "value", "start", "end", "range"],
            filter: Qe(a.filter, t)
          }
        ];
      }
    ),
    warnings: r,
    defaultInputValues: n.shared && Object.keys(n.shared).length > 0 ? n : void 0
  };
}
function kt(e) {
  var v, y;
  const t = Pe(e.plan);
  if (!t.ok)
    throw new Error(
      t.errors.map((c) => c.message).join(`
`) || "Dashboard plan is invalid."
    );
  const n = e.plan.sheets[0], r = [...t.warnings], o = [], a = new Map(
    e.cardArtifacts.map((c) => [c.planCardId, c])
  ), i = new Map(
    e.cardArtifacts.map((c) => [
      c.planCardId,
      c.card.id
    ])
  ), d = [];
  for (const c of n.cards) {
    const f = a.get(c.id);
    if (!f) {
      const l = ue(
        "missing_card_artifact",
        `Card "${c.title}" was skipped because no generated artifact was supplied.`,
        c.id
      );
      o.push(l);
      continue;
    }
    r.push(...f.warnings || []);
    const g = Ue(
      f.card,
      e.plan.calculatedFields,
      c.id
    );
    d.push({
      id: c.frameId,
      cards: [g],
      activeCardId: g.id
    });
  }
  if (d.length === 0)
    throw new Error("Dashboard plan did not produce any persistable cards.");
  const { inputs: s, defaultInputValues: u, warnings: h } = Xe(e.plan, i);
  r.push(...h);
  const I = K(
    n.cards.filter((c) => d.some((f) => f.id === c.frameId)).map((c) => ({
      frameId: c.frameId,
      priority: c.priority,
      role: c.role
    }))
  );
  return { dashboard: {
    id: e.dashboardId,
    title: e.plan.title,
    description: e.plan.description || "",
    sheets: [
      {
        id: n.id,
        kind: "dashboard",
        title: n.title,
        description: n.description,
        frames: d,
        layouts: I,
        calculatedFields: (v = e.plan.calculatedFields) == null ? void 0 : v.filter((c) => c.scope === "sheet" && c.field).map((c) => c.field)
      }
    ],
    calculatedFields: (y = e.plan.calculatedFields) == null ? void 0 : y.filter((c) => c.scope === "dashboard" && c.field).map((c) => c.field),
    inputs: s,
    ...u ? { defaultInputValues: u } : {}
  }, warnings: r, skippedOperations: o };
}
function x(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function Ye(e) {
  return JSON.parse(JSON.stringify(e));
}
function Ze(e) {
  var t;
  return (t = e.sheets) == null ? void 0 : t.find(
    (n) => (n.kind || "dashboard") === "dashboard"
  );
}
function R(e, t) {
  var n;
  for (const r of e.sheets || [])
    for (const o of r.frames || []) {
      const a = (n = o.cards) == null ? void 0 : n.find((i) => i.id === t);
      if (a)
        return { sheet: r, frame: o, card: a };
    }
  return null;
}
function fe(e) {
  var n, r;
  const t = (r = (n = e.cards) == null ? void 0 : n[0]) == null ? void 0 : r.type;
  return t === "kpi" ? "kpi" : t === "table" || t === "detailTable" || t === "pivotTable" ? "table" : t === "text" ? "text" : "chart";
}
function et(e) {
  var t;
  return new Map(
    (((t = e.layouts) == null ? void 0 : t.lg) || []).map((n, r) => [n.i, r])
  );
}
function pe(e, t = /* @__PURE__ */ new Map()) {
  const n = et(e), r = Math.max(
    n.size,
    t.size
  ), o = (e.frames || []).map(
    (a, i) => ({
      frameId: a.id,
      role: fe(a),
      priority: t.get(a.id) ?? n.get(a.id) ?? r + i
    })
  );
  e.layouts = K(o);
}
function tt(e) {
  return Object.values(e.layouts || {}).some((t) => t.length > 0);
}
function nt(e, t) {
  if (!tt(e)) {
    pe(e);
    return;
  }
  const n = K([
    { frameId: t.id, role: fe(t), priority: 0 }
  ]);
  e.layouts ?? (e.layouts = {});
  for (const [r, o] of Object.entries(n)) {
    const a = e.layouts[r] || [];
    if (a.some((s) => s.i === t.id))
      continue;
    const i = o[0];
    if (!i)
      continue;
    const d = a.reduce(
      (s, u) => Math.max(s, u.y + u.h),
      0
    );
    e.layouts[r] = [
      ...a,
      { ...i, y: d }
    ];
  }
}
function rt(e, t) {
  var r;
  const n = G(
    t.filter,
    t.defaultValue
  );
  n && (e.defaultInputValues ?? (e.defaultInputValues = {}), (r = e.defaultInputValues).shared ?? (r.shared = {}), e.defaultInputValues.shared[t.id] = {
    status: "set",
    value: {
      kind: "filter",
      filterValue: n
    }
  });
}
function xt(e) {
  var d;
  const t = ze(e.changePlan);
  if (!t.ok)
    throw new Error(
      t.errors.map((s) => s.message).join(`
`) || "Dashboard change plan is invalid."
    );
  const n = Ye(e.dashboard), r = [...t.warnings], o = [], a = new Map(
    e.cardArtifacts.map((s) => [s.planCardId, s])
  ), i = Ze(n);
  if (!i)
    throw new Error("Dashboard has no editable dashboard sheet.");
  i.frames ?? (i.frames = []);
  for (const s of e.changePlan.operations)
    switch (s.kind) {
      case "addCard": {
        if ((i.frames || []).reduce(
          (w, v) => {
            var y;
            return w + (((y = v.cards) == null ? void 0 : y.length) || 0);
          },
          0
        ) >= B) {
          o.push(
            x(
              "generated_card_limit_reached",
              `AI refinement is capped at ${B} cards.`,
              s.card.id
            )
          );
          break;
        }
        const h = a.get(s.card.id);
        if (!h) {
          o.push(
            x(
              "missing_card_artifact",
              `Card "${s.card.title}" was skipped because no generated artifact was supplied.`,
              s.card.id
            )
          );
          break;
        }
        const I = {
          id: s.card.frameId,
          cards: [h.card],
          activeCardId: h.card.id
        };
        i.frames.push(I), nt(i, I);
        break;
      }
      case "addFilterInput": {
        n.inputs ?? (n.inputs = []);
        const u = {
          id: s.input.id,
          kind: "filter",
          label: s.input.label,
          variableName: s.input.variableName,
          scope: s.input.scope || {
            kind: "allSheets",
            sheetKinds: ["dashboard"]
          },
          runtimeScope: "shared",
          presentation: {
            placement: "toolbar",
            order: n.inputs.length
          },
          exports: ["label", "value", "start", "end", "range"],
          filter: s.input.filter
        };
        n.inputs.push(u), rt(n, s.input);
        break;
      }
      case "addCalculatedField": {
        if (s.field.scope === "dashboard" && s.field.field)
          n.calculatedFields ?? (n.calculatedFields = []), n.calculatedFields.push(s.field.field);
        else if (s.field.scope === "sheet" && s.field.field)
          i.calculatedFields ?? (i.calculatedFields = []), i.calculatedFields.push(s.field.field);
        else if (s.field.scope === "card" && s.field.field) {
          const u = s.field.targetCardId ? R(n, s.field.targetCardId) : null;
          u ? ((d = u.card).calculatedFields ?? (d.calculatedFields = []), u.card.calculatedFields.push(s.field.field)) : o.push(
            x(
              "missing_calculated_field_target",
              `Calculated field "${s.field.name}" needs a valid target card.`
            )
          );
        }
        break;
      }
      case "renameCard": {
        const u = R(n, s.cardId);
        if (!u) {
          o.push(
            x(
              "card_not_found",
              `Card "${s.cardId}" could not be renamed because it was not found.`,
              s.cardId
            )
          );
          break;
        }
        u.card.title = s.title, s.description !== void 0 && (u.card.description = s.description);
        break;
      }
      case "reorderCards": {
        const u = /* @__PURE__ */ new Map();
        for (let h = 0; h < s.cardIds.length; h += 1) {
          const I = s.cardIds[h], w = R(n, I);
          w && u.set(w.frame.id, h);
        }
        pe(i, u);
        break;
      }
      case "reuseCalculatedField":
        r.push(
          x(
            "reused_calculated_field",
            `Calculated field "${s.fieldId}" is reused by reference.`
          )
        );
        break;
      case "unsupported":
        o.push(
          x("unsupported_operation", s.reason || s.requestedAction)
        );
        break;
    }
  return { dashboard: n, warnings: r, skippedOperations: o };
}
function b(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function F(e, t) {
  return e.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || t;
}
function he(e, t) {
  if (!t.has(e))
    return t.add(e), e;
  let n = 2, r = `${e}-${n}`;
  for (; t.has(r); )
    n += 1, r = `${e}-${n}`;
  return t.add(r), r;
}
function T(e) {
  return !!(e && typeof e == "object");
}
function me(e) {
  return Array.isArray(e.inputs) ? e.inputs.filter(
    (t) => T(t) && typeof t.id == "string"
  ) : [];
}
function U(e) {
  return Array.isArray(e.sections) ? e.sections.filter(
    (t) => T(t)
  ) : [];
}
function J(e) {
  return Array.isArray(e.views) ? e.views.filter(
    (t) => T(t)
  ) : [];
}
function D(e) {
  if (!Array.isArray(e))
    return [];
  const t = [];
  for (const n of e) {
    const r = S(n);
    r && t.push(r);
  }
  return t;
}
function at(e) {
  var r, o;
  if (!e)
    return [];
  const t = [];
  if (z(e.source) && t.push(e.source), e.kind === "metric") {
    t.push(...D(e.metrics));
    const a = S(e.dateField);
    a && t.push(a), t.push(...D(e.dimensions)), t.push(
      ...D(
        (r = e.filters) == null ? void 0 : r.map((i) => i.field)
      )
    );
  } else if (e.kind === "records") {
    const a = S(e.dateField);
    a && t.push(a), t.push(...D(e.fields)), t.push(
      ...D(
        (o = e.filters) == null ? void 0 : o.map((i) => i.field)
      )
    );
  } else if (e.kind === "inputOptions") {
    const a = S(e.field);
    a && t.push(a);
  } else e.kind === "sql" && t.push(...D(e.fields));
  const n = "inputs" in e && Array.isArray(e.inputs) ? e.inputs : [];
  for (const a of n) {
    const i = S(a.field);
    i && t.push(i);
  }
  return t;
}
function it(e) {
  const t = [];
  for (const n of me(e)) {
    const r = S(n.field);
    r && t.push(r);
  }
  for (const n of U(e))
    for (const r of J(n))
      t.push(...at(r.analytics));
  return t;
}
function ot(e) {
  var n;
  const t = [];
  for (const r of U(e))
    for (const o of J(r))
      z((n = o.analytics) == null ? void 0 : n.source) && t.push(o.analytics.source);
  return t;
}
function st(e, t) {
  const n = P(e).filter(z);
  if (n.length === 0)
    return t.push(
      b(
        "missing_materializable_dataset",
        "No semantic or physical source could be converted into the current dashboard authoring dataset reference."
      )
    ), [];
  const r = n.every((a) => a.kind === "semantic"), o = Array.from(
    new Set(
      n.filter((a) => a.kind === "semantic").map((a) => a.domainId)
    )
  );
  return n.length > 1 && (!r || o.length !== 1) ? (t.push(
    b(
      "multiple_datasets_out_of_scope",
      "The dashboard authoring compiler supports multiple datasets only within one semantic domain; using the first source and deferring the rest."
    )
  ), [n[0]]) : n;
}
function dt(e, t) {
  const n = U(e), r = me(e), o = P(it(e)), a = P(
    ot(e)
  );
  return {
    sections: n,
    inputs: r,
    sources: o,
    primarySources: a,
    defaultSource: a.length === 1 ? a[0] : void 0,
    datasets: st(o, t)
  };
}
function ct(e) {
  return e && ae(e).ok ? e : void 0;
}
function lt(e) {
  var t;
  switch ((t = e.presentation) == null ? void 0 : t.kind) {
    case "kpi":
      return "kpi";
    case "lineChart":
      return "line";
    case "barChart":
      return "bar";
    case "areaChart":
      return "area";
    case "table":
      return "table";
    case "text":
      return "text";
    default:
      return null;
  }
}
function ut(e) {
  var t, n, r;
  return ((t = e.presentation) == null ? void 0 : t.kind) === "kpi" ? "kpi" : ((n = e.presentation) == null ? void 0 : n.kind) === "table" ? "table" : ((r = e.presentation) == null ? void 0 : r.kind) === "text" ? "text" : "chart";
}
function ft(e) {
  const t = we(e);
  switch (t) {
    case "not_in":
      return "not in";
    case "not_between":
      return "not between";
    case "contains":
      return "like";
    case "not_contains":
      return "not like";
    default:
      return t || "in";
  }
}
function pt(e) {
  return T(e.field) ? e.field.dataType === "datetime" ? "date" : e.field.dataType || "string" : "string";
}
function ht(e) {
  if (!(!e || e.kind !== "physical"))
    return [e.databaseName, e.schemaName, e.tableName].filter(Boolean).join(".");
}
function mt(e, t, n, r, o, a) {
  if (e.kind !== "filter")
    return a.push(
      b(
        "control_inputs_deferred",
        `Control input "${e.label}" is represented in the protocol but not yet materialized by the dashboard authoring adapter.`
      )
    ), null;
  if (!T(e.field) || typeof e.field.name != "string")
    return a.push(
      b(
        "filter_requires_field",
        `Filter "${e.label || e.id}" needs a field before the dashboard compiler can materialize it.`
      )
    ), null;
  const i = ke({
    explicitSource: void 0,
    field: e.field,
    defaultSource: t,
    fallbackSources: n
  }), d = (i == null ? void 0 : i.kind) === "semantic" || (i == null ? void 0 : i.kind) === "physical" ? i.connectionId : void 0;
  if (!d)
    return a.push(
      b(
        "filter_requires_connection_id",
        `Filter "${e.label}" needs a source connectionId before the dashboard compiler can materialize it.`
      )
    ), null;
  const h = {
    id: `filter-${he(
      F(e.id, e.field.name),
      o
    )}`,
    variableName: e.id,
    connectionId: d,
    title: e.label,
    column: e.field.name,
    dataType: pt(e),
    qualifiedTableName: ht(i),
    sql: "",
    operation: ft(e.operator),
    type: e.multi === !1 ? "single" : "multiple",
    location: "dashboard",
    displayMode: "toolbar",
    fieldMeta: (i == null ? void 0 : i.kind) === "semantic" ? {
      name: e.field.name,
      qualifiedFieldName: e.field.name,
      dataType: e.field.dataType,
      role: e.field.role === "measure" ? "metric" : "groupby"
    } : void 0,
    semanticContext: (i == null ? void 0 : i.kind) === "semantic" ? {
      semanticDomainId: i.domainId,
      connectionId: i.connectionId
    } : void 0
  };
  return {
    id: e.id,
    label: e.label,
    variableName: e.id,
    scope: r,
    filter: h,
    defaultValue: G(
      h,
      e.defaultValue
    )
  };
}
function O(e) {
  const t = [], n = [];
  for (const r of e.viewIds) {
    const o = e.viewIdToCardId.get(r);
    o ? t.push(o) : n.push(r);
  }
  return n.length > 0 && e.warnings.push(
    b(
      "input_scope_view_not_found",
      `Filter "${e.inputLabel}" referenced unknown view ids: ${n.join(", ")}.`
    )
  ), Array.from(new Set(t));
}
function gt(e) {
  var r, o;
  if (!e.protocolScope) {
    const a = Array.from(new Set(e.boundCardIds));
    return a.length > 0 && a.length < e.allCardIds.length ? { kind: "cards", cardIds: a } : void 0;
  }
  if (e.protocolScope.level === "dashboard") {
    if (!((r = e.protocolScope.excludeViewIds) != null && r.length))
      return;
    const a = new Set(
      O({
        inputLabel: e.inputLabel,
        viewIds: e.protocolScope.excludeViewIds,
        viewIdToCardId: e.viewIdToCardId,
        warnings: e.warnings
      })
    );
    return {
      kind: "cards",
      cardIds: e.allCardIds.filter((i) => !a.has(i))
    };
  }
  if (e.protocolScope.level === "view") {
    const a = O({
      inputLabel: e.inputLabel,
      viewIds: e.protocolScope.viewIds,
      viewIdToCardId: e.viewIdToCardId,
      warnings: e.warnings
    });
    return a.length === 0 ? (e.warnings.push(
      b(
        "input_scope_has_no_materialized_cards",
        `Filter "${e.inputLabel}" was deferred because its view scope does not match any materialized cards.`
      )
    ), null) : { kind: "cards", cardIds: a };
  }
  const t = e.sectionIdToCardIds.get(e.protocolScope.sectionId) || [];
  if (t.length === 0)
    return e.warnings.push(
      b(
        "input_scope_section_not_found",
        `Filter "${e.inputLabel}" was deferred because section "${e.protocolScope.sectionId}" does not match any materialized cards.`
      )
    ), null;
  if (!((o = e.protocolScope.excludeViewIds) != null && o.length))
    return { kind: "cards", cardIds: t };
  const n = new Set(
    O({
      inputLabel: e.inputLabel,
      viewIds: e.protocolScope.excludeViewIds,
      viewIdToCardId: e.viewIdToCardId,
      warnings: e.warnings
    })
  );
  return {
    kind: "cards",
    cardIds: t.filter((a) => !n.has(a))
  };
}
function Dt(e) {
  var v, y, c;
  const t = [], n = _e(e);
  for (const f of n.warnings)
    t.push(b(f.code, f.message));
  for (const f of n.errors)
    t.push(b(f.code, f.message));
  const r = dt(e, t), o = [], a = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Set(), u = /* @__PURE__ */ new Set();
  let h = 0;
  for (const [f, g] of r.sections.entries()) {
    const l = typeof g.title == "string" ? g.title : `Section ${f + 1}`, Q = g.id || F(l, `section-${f + 1}`);
    i.set(Q, []);
    for (const [X, m] of J(g).entries()) {
      const Y = lt(m), V = F(
        m.id || `${l}-${m.title || `View ${X + 1}`}`,
        `card-${f + 1}-${X + 1}`
      );
      if (!Y) {
        t.push(
          b(
            "unsupported_presentation",
            `Dashboard presentation "${((v = m.presentation) == null ? void 0 : v.kind) || "unknown"}" is not supported by the dashboard authoring adapter.`,
            `card-${V}`
          )
        );
        continue;
      }
      if (((y = m.analytics) == null ? void 0 : y.kind) === "sql") {
        t.push(
          b(
            "sql_intent_deferred",
            "SQL analytics intent is valid protocol, but the current dashboard authoring adapter only materializes semantic and physical config-card intents.",
            `card-${V}`
          )
        );
        continue;
      }
      const Z = he(V, s), $ = `card-${Z}`;
      m.id && a.set(m.id, $), (c = i.get(Q)) == null || c.push($);
      const ge = m.analytics && "inputs" in m.analytics ? m.analytics.inputs : void 0;
      for (const ee of ge || []) {
        const te = d.get(ee.inputId) || [];
        te.push($), d.set(ee.inputId, te);
      }
      o.push({
        id: $,
        frameId: `frame-${Z}`,
        title: m.title,
        description: m.description,
        type: Y,
        role: ut(m),
        priority: h,
        section: l,
        analyticsIntent: ct(m.analytics),
        text: m.text
      }), h += 1;
    }
  }
  const I = r.inputs.map((f) => {
    const g = gt({
      protocolScope: f.scope,
      inputLabel: f.label,
      allCardIds: o.map((l) => l.id),
      boundCardIds: d.get(f.id) || [],
      viewIdToCardId: a,
      sectionIdToCardIds: i,
      warnings: t
    });
    return g === null ? null : mt(
      f,
      r.defaultSource,
      r.sources,
      g,
      u,
      t
    );
  }).filter((f) => !!f);
  return { plan: {
    version: 1,
    id: `plan-${F(e.title, "dashboard")}`,
    title: e.title,
    description: e.description,
    datasets: r.datasets,
    sheets: [
      {
        id: `sheet-${F(e.title, "dashboard")}`,
        title: e.title,
        description: e.description,
        kind: "dashboard",
        cards: o
      }
    ],
    filterInputs: I.length ? I : void 0,
    warnings: t.length ? t : void 0,
    unresolvedRequests: n.ok ? void 0 : n.errors.map((f) => f.message)
  }, warnings: t };
}
export {
  be as DASHBOARD_AUTHORING_BREAKPOINTS,
  B as DASHBOARD_AUTHORING_MAX_GENERATED_CARDS,
  xt as applyDashboardChangePlan,
  kt as compileDashboardFromPlan,
  K as compileResponsiveDashboardLayouts,
  H as dashboardAuthoringDatasetMatchesSource,
  St as dashboardAuthoringFieldsReferToSameTarget,
  S as dashboardAuthoringSourceFromField,
  wt as dashboardAuthoringSourceKey,
  ie as dashboardAuthoringSourcesReferToSameDataset,
  Dt as dashboardPlanFromSemaphorDashboardIntent,
  Ct as findDashboardAuthoringDatasetForSource,
  Me as getDashboardAuthoringCardSource,
  z as isMaterializableDashboardAuthoringSource,
  Se as isSemaphorSourceRef,
  P as mergeDashboardAuthoringSources,
  Ce as preferDashboardAuthoringSourceMetadata,
  vt as preferredDashboardAuthoringSource,
  ke as resolveDashboardAuthoringSource,
  Ne as validateDashboardAuthoringDatasetScope,
  ze as validateDashboardChangePlan,
  Pe as validateDashboardPlan
};
