import { D as B, a as ge } from "../chunks/contracts-CoCOpd_i.js";
import { a as be, b as E, p as Ie } from "../chunks/source-identity-qAmkNtEK.js";
import { v as re, c as ye } from "../chunks/validators-BnLhuIhd.js";
import { b as _e } 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 we(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 V(e) {
  return we(e) ? e.kind === "semantic" ? !!(e.domainId && e.datasetName) : e.kind === "physical" ? !!(e.connectionId && e.tableName) : !1 : !1;
}
function _t(e) {
  return be(e);
}
function ae(e, t) {
  return E(e, t);
}
function ve(e, t) {
  return Ie(e, t);
}
function P(e) {
  const t = [];
  for (const n of e) {
    const r = t.findIndex(
      (i) => ae(i, n)
    );
    r === -1 ? t.push(n) : t[r] = ve(
      t[r],
      n
    );
  }
  return t;
}
function wt(e) {
  return P(e)[0];
}
function O(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 V(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 ? O(n, t) : void 0;
}
function Se({
  explicitSource: e,
  field: t,
  defaultSource: n,
  fallbackSources: r
}) {
  const i = [n, ...r || []], a = j(e), o = a ? O(
    a,
    ne(a, i)
  ) : void 0;
  if (o)
    return o;
  if (e !== void 0)
    return;
  const d = S(t, n), s = d ? O(
    d,
    ne(d, i)
  ) : void 0;
  if (s)
    return s;
  if ((t == null ? void 0 : t.source) === void 0)
    return j(n);
}
function vt(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 : ae(n, r);
}
function k(e) {
  var t;
  return C((t = _(e)) == null ? void 0 : t.kind);
}
function ie(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 Ce(e) {
  var t;
  return k(e) !== "semantic" ? null : C((t = _(e)) == null ? void 0 : t.datasetName);
}
function ke(e) {
  var t;
  return k(e) !== "semantic" ? null : C((t = _(e)) == null ? void 0 : t.datasetId);
}
function xe(e) {
  var t;
  return k(e) !== "physical" ? null : C((t = _(e)) == null ? void 0 : t.connectionId);
}
function De(e) {
  var t;
  return k(e) !== "physical" ? null : C((t = _(e)) == null ? void 0 : t.tableName);
}
function Ae(e) {
  var t;
  return k(e) !== "physical" ? "" : C((t = _(e)) == null ? void 0 : t.databaseName) || "";
}
function Fe(e) {
  var t;
  return k(e) !== "physical" ? "" : C((t = _(e)) == null ? void 0 : t.schemaName) || "";
}
function Te(e) {
  if (e.analyticsIntent && typeof e.analyticsIntent == "object" && "source" in e.analyticsIntent)
    return e.analyticsIntent.source;
}
function $e({
  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(ie), r = new Set(n.filter(Boolean));
  return n.some((i) => !i) || 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 = ke(e);
    return ie(e) === t.domainId ? n && t.datasetId ? n === t.datasetId : Ce(e) === t.datasetName : !1;
  }
  return t.kind === "physical" ? xe(e) === t.connectionId && De(e) === t.tableName && Ae(e) === (t.databaseName || "") && Fe(e) === (t.schemaName || "") : !1;
}
function St(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 oe({
  card: e,
  datasets: t,
  errors: n
}) {
  if (e.type === "text")
    return;
  const r = Te(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((i) => H(i, 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 Me(e) {
  return Array.isArray(e) ? e.filter(
    (t) => !!(t && typeof t == "object")
  ) : [];
}
function Ne(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),
      ...Me(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
    ])
  ) : e.kind === "inputOptions" ? t.push(...N([e.field])) : e.kind === "sql" && t.push(...N(e.fields || [])), t;
}
function se({
  card: e,
  datasets: t,
  errors: n
}) {
  if (e.type !== "text") {
    for (const r of Ne(e.analyticsIntent))
      if (r && !t.some(
        (i) => H(i, r)
      )) {
        n.push(
          p(
            "invalid_card_query_source",
            "Dashboard card query field references must use one of the selected datasets.",
            e.id
          )
        );
        return;
      }
  }
}
function de({
  card: e,
  errors: t
}) {
  if (e.type === "text" || !e.analyticsIntent)
    return;
  const n = re(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 ce({
  datasets: e,
  errors: t,
  requireAtLeastOne: n
}) {
  const r = $e({
    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 Be(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 i = Array.isArray(n.datasets) ? n.datasets : [], a = Array.isArray(n.sheets) ? n.sheets : [];
  ce({ datasets: i, errors: t, requireAtLeastOne: !0 }), a.length !== 1 && t.push(
    p(
      "invalid_sheet_count",
      "MVP dashboard authoring creates exactly one dashboard sheet."
    )
  );
  const o = a[0];
  o && o.kind !== "dashboard" && t.push(
    p("invalid_sheet_kind", 'Generated sheet must use kind "dashboard".')
  );
  const d = (o == null ? void 0 : o.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
      )
    ), oe({ card: l, datasets: i, errors: t }), de({ card: l, errors: t }), se({ card: l, datasets: i, 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 Pe(e) {
  var o;
  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.")
  ), (o = n.dashboardId) != null && o.trim() || t.push(
    p("missing_dashboard_id", "Dashboard change plan needs a dashboard id.")
  );
  const i = Array.isArray(n.datasets) ? n.datasets : [], a = Array.isArray(n.operations) ? n.operations : [];
  ce({ datasets: i, 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" && (oe({
      card: d.card,
      datasets: i,
      errors: t
    }), de({
      card: d.card,
      errors: t
    }), se({
      card: d.card,
      datasets: i,
      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 ze(e, t) {
  let n = 0, r = 0, i = 0;
  return e.map((a) => {
    const o = Math.min(a.w, t);
    n > 0 && n + o > t && (n = 0, r += i, i = 0);
    const d = {
      i: a.frameId,
      x: n,
      y: r,
      w: o,
      h: a.h,
      minW: Math.min(a.minW, t),
      minH: a.minH,
      static: !1
    };
    return n += o, i = Math.max(i, a.h), d;
  });
}
function qe(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"), i = t.filter((s) => s.role === "table"), a = t.filter((s) => s.role === "text"), o = a.slice(0, 1), d = a.slice(o.length);
  return { kpis: n, introText: o, charts: r, tables: i, supportingText: d };
}
function Re(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 Oe(e) {
  const { item: t, band: n, index: r, bandCount: i, breakpoint: a, columns: o } = e;
  return n === "kpi" ? {
    ...t,
    band: n,
    w: Re(i, a, o),
    h: 15,
    minW: Math.min(6, o),
    minH: 12
  } : n === "table" ? {
    ...t,
    band: n,
    w: o,
    h: a === "xxs" || a === "xs" ? 34 : 38,
    minW: Math.min(12, o),
    minH: 18
  } : n === "introText" ? {
    ...t,
    band: n,
    w: o,
    h: a === "xxs" || a === "xs" ? 12 : 10,
    minW: Math.min(12, o),
    minH: 8
  } : n === "supportingText" ? {
    ...t,
    band: n,
    w: a === "lg" ? o / 2 : o,
    h: a === "xxs" || a === "xs" ? 12 : 10,
    minW: Math.min(12, o),
    minH: 8
  } : {
    ...t,
    band: n,
    w: Le(r, i, a, o),
    h: a === "xxs" || a === "xs" ? 28 : 30,
    minW: Math.min(12, o),
    minH: 16
  };
}
function D(e, t, n, r) {
  return e.map(
    (i, a) => Oe({
      item: i,
      band: t,
      index: a,
      bandCount: e.length,
      breakpoint: n,
      columns: r
    })
  );
}
function K(e) {
  const t = qe(e);
  return Object.fromEntries(
    ge.map((n) => {
      const r = Ve[n], i = [
        ...D(t.introText, "introText", n, r),
        ...D(t.kpis, "kpi", n, r),
        ...D(t.charts, "chart", n, r),
        ...D(t.tables, "table", n, r),
        ...D(t.supportingText, "supportingText", n, r)
      ];
      return [n, ze(i, r)];
    })
  );
}
function je(e) {
  const t = _e(e);
  return t === "datetime" ? "date" : t === "unknown" ? "string" : t;
}
function We(e) {
  return !!(e && typeof e == "object" && !Array.isArray(e));
}
function Ee(e) {
  return We(e) && typeof e.filterId == "string" && typeof e.operation == "string" && Array.isArray(e.values);
}
function He(e) {
  return e.filter(
    (t) => typeof t == "string" || typeof t == "number"
  );
}
function Ke(e) {
  return e.filter(
    (t) => t instanceof Date || typeof t == "string"
  );
}
function G(e, t) {
  if (t === void 0)
    return;
  const n = je(e.dataType), r = e.operation || "in";
  if (Ee(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 i = Array.isArray(t) ? t : [t], a = n === "date" ? Ke(i) : He(i);
  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 le(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function Ge(e, t, n) {
  const r = (t || []).filter(
    (i) => i.scope === "card" && i.targetCardId === n
  ).map((i) => i.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 Ue(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 Je(e, t) {
  return !e.applyToCardIds && !e.excludeCardIds ? e : {
    ...e,
    ...e.applyToCardIds ? {
      applyToCardIds: W(
        e.applyToCardIds,
        t
      )
    } : {},
    ...e.excludeCardIds ? {
      excludeCardIds: W(
        e.excludeCardIds,
        t
      )
    } : {}
  };
}
function Qe(e, t) {
  const n = {}, r = [];
  return {
    inputs: (e.filterInputs || []).flatMap(
      (a, o) => {
        const d = Ue(a.scope, t);
        if (d === null)
          return r.push(
            le(
              "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: o
            },
            exports: ["label", "value", "start", "end", "range"],
            filter: Je(a.filter, t)
          }
        ];
      }
    ),
    warnings: r,
    defaultInputValues: n.shared && Object.keys(n.shared).length > 0 ? n : void 0
  };
}
function Ct(e) {
  var v, y;
  const t = Be(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], i = [], a = new Map(
    e.cardArtifacts.map((c) => [c.planCardId, c])
  ), o = 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 = le(
        "missing_card_artifact",
        `Card "${c.title}" was skipped because no generated artifact was supplied.`,
        c.id
      );
      i.push(l);
      continue;
    }
    r.push(...f.warnings || []);
    const g = Ge(
      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 } = Qe(e.plan, o);
  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: i };
}
function x(e, t, n) {
  return n ? { code: e, message: t, cardId: n } : { code: e, message: t };
}
function Xe(e) {
  return JSON.parse(JSON.stringify(e));
}
function Ye(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 i of r.frames || []) {
      const a = (n = i.cards) == null ? void 0 : n.find((o) => o.id === t);
      if (a)
        return { sheet: r, frame: i, card: a };
    }
  return null;
}
function ue(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 Ze(e) {
  var t;
  return new Map(
    (((t = e.layouts) == null ? void 0 : t.lg) || []).map((n, r) => [n.i, r])
  );
}
function fe(e, t = /* @__PURE__ */ new Map()) {
  const n = Ze(e), r = Math.max(
    n.size,
    t.size
  ), i = (e.frames || []).map(
    (a, o) => ({
      frameId: a.id,
      role: ue(a),
      priority: t.get(a.id) ?? n.get(a.id) ?? r + o
    })
  );
  e.layouts = K(i);
}
function et(e) {
  return Object.values(e.layouts || {}).some((t) => t.length > 0);
}
function tt(e, t) {
  if (!et(e)) {
    fe(e);
    return;
  }
  const n = K([
    { frameId: t.id, role: ue(t), priority: 0 }
  ]);
  e.layouts ?? (e.layouts = {});
  for (const [r, i] of Object.entries(n)) {
    const a = e.layouts[r] || [];
    if (a.some((s) => s.i === t.id))
      continue;
    const o = i[0];
    if (!o)
      continue;
    const d = a.reduce(
      (s, u) => Math.max(s, u.y + u.h),
      0
    );
    e.layouts[r] = [
      ...a,
      { ...o, y: d }
    ];
  }
}
function nt(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 kt(e) {
  var d;
  const t = Pe(e.changePlan);
  if (!t.ok)
    throw new Error(
      t.errors.map((s) => s.message).join(`
`) || "Dashboard change plan is invalid."
    );
  const n = Xe(e.dashboard), r = [...t.warnings], i = [], a = new Map(
    e.cardArtifacts.map((s) => [s.planCardId, s])
  ), o = Ye(n);
  if (!o)
    throw new Error("Dashboard has no editable dashboard sheet.");
  o.frames ?? (o.frames = []);
  for (const s of e.changePlan.operations)
    switch (s.kind) {
      case "addCard": {
        if ((o.frames || []).reduce(
          (w, v) => {
            var y;
            return w + (((y = v.cards) == null ? void 0 : y.length) || 0);
          },
          0
        ) >= B) {
          i.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) {
          i.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
        };
        o.frames.push(I), tt(o, 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), nt(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)
          o.calculatedFields ?? (o.calculatedFields = []), o.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)) : i.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) {
          i.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);
        }
        fe(o, u);
        break;
      }
      case "reuseCalculatedField":
        r.push(
          x(
            "reused_calculated_field",
            `Calculated field "${s.fieldId}" is reused by reference.`
          )
        );
        break;
      case "unsupported":
        i.push(
          x("unsupported_operation", s.reason || s.requestedAction)
        );
        break;
    }
  return { dashboard: n, warnings: r, skippedOperations: i };
}
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 pe(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 he(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 A(e) {
  if (!Array.isArray(e))
    return [];
  const t = [];
  for (const n of e) {
    const r = S(n);
    r && t.push(r);
  }
  return t;
}
function rt(e) {
  var r;
  if (!e)
    return [];
  const t = [];
  if (V(e.source) && t.push(e.source), e.kind === "metric") {
    t.push(...A(e.metrics));
    const i = S(e.dateField);
    i && t.push(i), t.push(...A(e.dimensions)), t.push(
      ...A(
        (r = e.filters) == null ? void 0 : r.map((a) => a.field)
      )
    );
  } else if (e.kind === "records") {
    const i = S(e.dateField);
    i && t.push(i), t.push(...A(e.fields));
  } else if (e.kind === "inputOptions") {
    const i = S(e.field);
    i && t.push(i);
  } else e.kind === "sql" && t.push(...A(e.fields));
  const n = "inputs" in e && Array.isArray(e.inputs) ? e.inputs : [];
  for (const i of n) {
    const a = S(i.field);
    a && t.push(a);
  }
  return t;
}
function at(e) {
  const t = [];
  for (const n of he(e)) {
    const r = S(n.field);
    r && t.push(r);
  }
  for (const n of U(e))
    for (const r of J(n))
      t.push(...rt(r.analytics));
  return t;
}
function it(e) {
  var n;
  const t = [];
  for (const r of U(e))
    for (const i of J(r))
      V((n = i.analytics) == null ? void 0 : n.source) && t.push(i.analytics.source);
  return t;
}
function ot(e, t) {
  const n = P(e).filter(V);
  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"), i = Array.from(
    new Set(
      n.filter((a) => a.kind === "semantic").map((a) => a.domainId)
    )
  );
  return n.length > 1 && (!r || i.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 st(e, t) {
  const n = U(e), r = he(e), i = P(at(e)), a = P(
    it(e)
  );
  return {
    sections: n,
    inputs: r,
    sources: i,
    primarySources: a,
    defaultSource: a.length === 1 ? a[0] : void 0,
    datasets: ot(i, t)
  };
}
function dt(e) {
  return e && re(e).ok ? e : void 0;
}
function ct(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 lt(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 ut(e) {
  switch (e) {
    case "not_in":
      return "not in";
    case "not_between":
      return "not between";
    case "contains":
      return "like";
    default:
      return e || "in";
  }
}
function ft(e) {
  return T(e.field) ? e.field.dataType === "datetime" ? "date" : e.field.dataType || "string" : "string";
}
function pt(e) {
  if (!(!e || e.kind !== "physical"))
    return [e.databaseName, e.schemaName, e.tableName].filter(Boolean).join(".");
}
function ht(e, t, n, r, i, 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 o = Se({
    explicitSource: void 0,
    field: e.field,
    defaultSource: t,
    fallbackSources: n
  }), d = (o == null ? void 0 : o.kind) === "semantic" || (o == null ? void 0 : o.kind) === "physical" ? o.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-${pe(
      F(e.id, e.field.name),
      i
    )}`,
    variableName: e.id,
    connectionId: d,
    title: e.label,
    column: e.field.name,
    dataType: ft(e),
    qualifiedTableName: pt(o),
    sql: "",
    operation: ut(e.operator),
    type: e.multi === !1 ? "single" : "multiple",
    location: "dashboard",
    displayMode: "toolbar",
    fieldMeta: (o == null ? void 0 : o.kind) === "semantic" ? {
      name: e.field.name,
      qualifiedFieldName: e.field.name,
      dataType: e.field.dataType,
      role: e.field.role === "measure" ? "metric" : "groupby"
    } : void 0,
    semanticContext: (o == null ? void 0 : o.kind) === "semantic" ? {
      semanticDomainId: o.domainId,
      connectionId: o.connectionId
    } : void 0
  };
  return {
    id: e.id,
    label: e.label,
    variableName: e.id,
    scope: r,
    filter: h,
    defaultValue: G(
      h,
      e.defaultValue
    )
  };
}
function L(e) {
  const t = [], n = [];
  for (const r of e.viewIds) {
    const i = e.viewIdToCardId.get(r);
    i ? t.push(i) : 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 mt(e) {
  var r, i;
  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(
      L({
        inputLabel: e.inputLabel,
        viewIds: e.protocolScope.excludeViewIds,
        viewIdToCardId: e.viewIdToCardId,
        warnings: e.warnings
      })
    );
    return {
      kind: "cards",
      cardIds: e.allCardIds.filter((o) => !a.has(o))
    };
  }
  if (e.protocolScope.level === "view") {
    const a = L({
      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 (!((i = e.protocolScope.excludeViewIds) != null && i.length))
    return { kind: "cards", cardIds: t };
  const n = new Set(
    L({
      inputLabel: e.inputLabel,
      viewIds: e.protocolScope.excludeViewIds,
      viewIdToCardId: e.viewIdToCardId,
      warnings: e.warnings
    })
  );
  return {
    kind: "cards",
    cardIds: t.filter((a) => !n.has(a))
  };
}
function xt(e) {
  var v, y, c;
  const t = [], n = ye(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 = st(e, t), i = [], a = /* @__PURE__ */ new Map(), o = /* @__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}`);
    o.set(Q, []);
    for (const [X, m] of J(g).entries()) {
      const Y = ct(m), z = 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-${z}`
          )
        );
        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-${z}`
          )
        );
        continue;
      }
      const Z = pe(z, s), $ = `card-${Z}`;
      m.id && a.set(m.id, $), (c = o.get(Q)) == null || c.push($);
      const me = m.analytics && "inputs" in m.analytics ? m.analytics.inputs : void 0;
      for (const ee of me || []) {
        const te = d.get(ee.inputId) || [];
        te.push($), d.set(ee.inputId, te);
      }
      i.push({
        id: $,
        frameId: `frame-${Z}`,
        title: m.title,
        description: m.description,
        type: Y,
        role: lt(m),
        priority: h,
        section: l,
        analyticsIntent: dt(m.analytics),
        text: m.text
      }), h += 1;
    }
  }
  const I = r.inputs.map((f) => {
    const g = mt({
      protocolScope: f.scope,
      inputLabel: f.label,
      allCardIds: i.map((l) => l.id),
      boundCardIds: d.get(f.id) || [],
      viewIdToCardId: a,
      sectionIdToCardIds: o,
      warnings: t
    });
    return g === null ? null : ht(
      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: i
      }
    ],
    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 {
  ge as DASHBOARD_AUTHORING_BREAKPOINTS,
  B as DASHBOARD_AUTHORING_MAX_GENERATED_CARDS,
  kt as applyDashboardChangePlan,
  Ct as compileDashboardFromPlan,
  K as compileResponsiveDashboardLayouts,
  H as dashboardAuthoringDatasetMatchesSource,
  vt as dashboardAuthoringFieldsReferToSameTarget,
  S as dashboardAuthoringSourceFromField,
  _t as dashboardAuthoringSourceKey,
  ae as dashboardAuthoringSourcesReferToSameDataset,
  xt as dashboardPlanFromSemaphorDashboardIntent,
  St as findDashboardAuthoringDatasetForSource,
  Te as getDashboardAuthoringCardSource,
  V as isMaterializableDashboardAuthoringSource,
  we as isSemaphorSourceRef,
  P as mergeDashboardAuthoringSources,
  ve as preferDashboardAuthoringSourceMetadata,
  wt as preferredDashboardAuthoringSource,
  Se as resolveDashboardAuthoringSource,
  $e as validateDashboardAuthoringDatasetScope,
  Pe as validateDashboardChangePlan,
  Be as validateDashboardPlan
};
