import { computed, inject, provide, shallowRef } from "vue";
import { injectLocal, provideLocal } from "@vueuse/core";
export const SCOPE_ADDRESS_VAR = "__scopes__";
export const SELECTIONS_VAR = "selections";
const CEL_CONTEXT_KEY = Symbol("cel-context");
export function provideCELContext(context) {
  const parent = injectLocal(CEL_CONTEXT_KEY, {});
  provideLocal(CEL_CONTEXT_KEY, { ...parent, ...context });
}
export function injectCELContext() {
  return injectLocal(CEL_CONTEXT_KEY, {});
}
function resolveScopeAccessor(accessor) {
  const resolved = {};
  for (const [member, thunk] of Object.entries(accessor)) resolved[member] = thunk();
  return resolved;
}
export function provideScopeAddress(uuid, accessor) {
  const parentScopes = injectCELContext()[SCOPE_ADDRESS_VAR];
  provideCELContext({
    [SCOPE_ADDRESS_VAR]: {
      type: "map<string, dyn>",
      label: "\u8DE8\u5C42\u4F5C\u7528\u57DF",
      description: '\u6309 UUID \u5BFB\u5740\u88AB\u906E\u853D\u7684\u7956\u5148\u4F5C\u7528\u57DF\uFF08\u5982 `__scopes__["<uuid>"].row`\uFF09\uFF1B\u4EC5\u80FD\u547D\u4E2D\u8BCD\u6CD5\u4E0A\u5305\u4F4F\u5F53\u524D\u4F4D\u7F6E\u7684\u4F5C\u7528\u57DF\u3002',
      // Resolved fresh each binding pass: invoke the parent thunk for live
      // ancestor rows, then overlay this uuid. Picker-stored expressions index
      // this by uuid; a uuid not on the ancestor chain is simply absent, so
      // bracket access throws a located `No such key` at the offending uuid.
      value: () => {
        const base = parentScopes ? typeof parentScopes.value === "function" ? parentScopes.value() : parentScopes.value : {};
        return { ...base, [uuid]: resolveScopeAccessor(accessor) };
      }
    }
  });
}
const SCOPE_ANCESTRY_KEY = Symbol("cel-scope-ancestry");
export function provideScopeAncestor(ancestor) {
  const parent = inject(SCOPE_ANCESTRY_KEY, void 0);
  provide(
    SCOPE_ANCESTRY_KEY,
    computed(() => {
      const chain = parent?.value ?? [];
      return ancestor.value ? [ancestor.value, ...chain] : chain;
    })
  );
}
export function useScopeAncestry() {
  return inject(SCOPE_ANCESTRY_KEY, void 0) ?? shallowRef([]);
}
const SELECTION_ROSTER_KEY = Symbol("cel-selection-roster");
export function provideSelectionRoster(roster) {
  provide(SELECTION_ROSTER_KEY, roster);
}
export function useSelectionRoster() {
  return inject(SELECTION_ROSTER_KEY, void 0) ?? shallowRef([]);
}
export function celBindings(context) {
  const out = {};
  for (const [name, entry] of Object.entries(context)) {
    out[name] = typeof entry.value === "function" ? entry.value() : entry.value;
  }
  return out;
}
