"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var Commands_exports = {};
__export(Commands_exports, {
  Commands: () => Commands
});
module.exports = __toCommonJS(Commands_exports);
var import_LocalActorContext = require("#behavior/context/server/LocalActorContext.js");
var import_general = require("#general");
/**
 * @license
 * Copyright 2022-2025 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
function Commands(endpoint) {
  const commands = {};
  return new Proxy(commands, {
    get(target, property, receiver) {
      if (Object.hasOwn(commands, property)) {
        return commands[property];
      }
      const behavior = endpoint.behaviors.supported[property];
      if (typeof behavior === "function" && "schema" in behavior) {
        return commands[property] = BehaviorCommands(endpoint, behavior);
      }
      return Reflect.get(target, property, receiver);
    }
  });
}
function BehaviorCommands(endpoint, type) {
  return new Proxy(
    {},
    {
      get(target, property, receiver) {
        if (typeof property !== "string" || property in Object.prototype) {
          return Reflect.get(target, property, receiver);
        }
        return Implementation(endpoint, type, property);
      }
    }
  );
}
function Implementation(endpoint, type, name) {
  return {
    [name](input, context) {
      if (context) {
        return Promise.resolve(invokerFor(context)(input, context));
      }
      const context2 = import_LocalActorContext.LocalActorContext.open(`invoke-${name}`, { lifetime: endpoint.construction });
      try {
        return Promise.resolve(context2.resolve(invokerFor(context2)(input, context)));
      } catch (e) {
        return Promise.resolve(context2.reject(e));
      }
      function invokerFor(context3) {
        const agent = endpoint.agentFor(context3);
        const behavior = agent.get(type);
        const method = behavior[name];
        if (typeof method !== "function") {
          throw new import_general.NotImplementedError(`Command ${name} is not implemented`);
        }
        return method.bind(behavior);
      }
    }
  }[name];
}
//# sourceMappingURL=Commands.js.map
