import { Effect, Option } from "effect";
import { Decimal } from "../vendor/cel-js/lib/decimal.js";
import { Environment } from "../vendor/cel-js/lib/index.js";
function unwrapCelValue(value) {
  if (value === null || value === void 0) return value;
  if (value instanceof Decimal) return value.toNumber();
  if (Option.isOption(value)) {
    return Option.isSome(value) ? unwrapCelValue(value.value) : void 0;
  }
  if (Array.isArray(value)) return value.map(unwrapCelValue);
  if (typeof value === "object") {
    const proto = Object.getPrototypeOf(value);
    if (proto !== Object.prototype && proto !== null) return value;
    const out = {};
    for (const key of Object.keys(value)) {
      out[key] = unwrapCelValue(value[key]);
    }
    return out;
  }
  return value;
}
const env = new Environment({ unlistedVariablesAreDyn: true });
env.registerFunction(
  "media(string): bool",
  (_self, q) => typeof window !== "undefined" && window.matchMedia(q).matches
);
env.registerFunction(
  "list<number>.sum(): number",
  (list) => list.reduce(
    (acc, n) => acc.add(n),
    Decimal.from(0)
  )
);
export function cel(expression, context) {
  return Effect.map(
    env.evaluate(expression, context),
    (v) => unwrapCelValue(v)
  );
}
export function celCheck(expression) {
  return env.check(expression);
}
