"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 ServerEndpointInitializer_exports = {};
__export(ServerEndpointInitializer_exports, {
  ServerEndpointInitializer: () => ServerEndpointInitializer
});
module.exports = __toCommonJS(ServerEndpointInitializer_exports);
var import_FabricScopedDataHandler = require("#behavior/cluster/FabricScopedDataHandler.js");
var import_ServerBehaviorBacking = require("#behavior/internal/ServerBehaviorBacking.js");
var import_Endpoint = require("#endpoint/Endpoint.js");
var import_EndpointVariableService = require("#endpoint/EndpointVariableService.js");
var import_EndpointInitializer = require("#endpoint/properties/EndpointInitializer.js");
var import_ServerNodeStore = require("#storage/server/ServerNodeStore.js");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_DescriptorServer = require("../../behaviors/descriptor/DescriptorServer.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("BehaviorInit");
class ServerEndpointInitializer extends import_EndpointInitializer.EndpointInitializer {
  #store;
  constructor(environment) {
    super();
    this.#store = environment.get(import_ServerNodeStore.ServerNodeStore);
    this.variableService = new import_EndpointVariableService.EndpointVariableService(environment);
  }
  initializeDescendant(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      endpoint.id = this.#identifyPart(endpoint);
    }
    this.#store.endpointStores.assignNumber(endpoint);
    if (!(import_DescriptorServer.DescriptorServer.id in endpoint.behaviors.supported)) {
      endpoint.behaviors.inject(import_DescriptorServer.DescriptorServer, void 0, false);
    }
  }
  async eraseDescendant(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      return;
    }
    await this.#store.endpointStores.eraseStoreForEndpoint(endpoint);
  }
  async deactivateDescendant(endpoint) {
    if (!endpoint.lifecycle.hasId || endpoint.number === 0) {
      return;
    }
    this.#store.endpointStores.deactivateStoreForEndpoint(endpoint);
  }
  /**
   * Create the backing.
   *
   * If the behavior is a cluster behavior and the node is already initialized, create a server when the behavior
   * initializes.
   */
  createBacking(endpoint, type) {
    const store = this.#store.storeForEndpoint(endpoint).createStoreForBehavior(type.id);
    return new import_ServerBehaviorBacking.ServerBehaviorBacking(endpoint, type, store, endpoint.behaviors.optionsFor(type));
  }
  /**
   * Select an ID for an endpoint automatically based on available metadata.
   */
  #identifyPart(endpoint) {
    const basicInfo = endpoint.behaviors.supported.basicInformation ?? endpoint.behaviors.supported.bridgedDeviceBasicInformation;
    if (basicInfo) {
      const defaults = {
        ...new basicInfo.State(),
        ...endpoint.behaviors.defaultsFor(basicInfo)
      };
      let id2 = defaults.uniqueId;
      if (id2) {
        return id2;
      }
      id2 = defaults.serialNumber;
      if (id2) {
        return id2;
      }
    }
    if (!(endpoint.owner instanceof import_Endpoint.Endpoint)) {
      throw new import_general.InternalError("Cannot determine ID for endpoint with unknown parent type");
    }
    if (!endpoint.owner.lifecycle.hasId) {
      throw new import_general.InternalError("Cannot determine ID for endpoint because parent has no ID");
    }
    const index = endpoint.owner.parts.indexOf(endpoint);
    if (index === -1) {
      throw new import_general.InternalError("Cannot determine ID for endpoint because parent does not list as child");
    }
    const id = `part${index}`;
    logger.warn(`Using fallback ID of ${id} for child of ${endpoint.owner}; assign ID to remove this warning`);
    return id;
  }
  behaviorsInitialized(agent) {
    if (agent.env.has(import_protocol.FabricManager)) {
      const fabricIndices = agent.env.get(import_protocol.FabricManager).fabrics.map((fabric) => fabric.fabricIndex);
      if (fabricIndices.length > 0) {
        return (0, import_FabricScopedDataHandler.limitEndpointAttributeDataToAllowedFabrics)(agent, fabricIndices);
      }
    }
  }
}
//# sourceMappingURL=ServerEndpointInitializer.js.map
