/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { limitEndpointAttributeDataToAllowedFabrics } from "#behavior/cluster/FabricScopedDataHandler.js";
import { ServerBehaviorBacking } from "#behavior/internal/ServerBehaviorBacking.js";
import { Endpoint } from "#endpoint/Endpoint.js";
import { EndpointVariableService } from "#endpoint/EndpointVariableService.js";
import { EndpointInitializer } from "#endpoint/properties/EndpointInitializer.js";
import { ServerNodeStore } from "#storage/server/ServerNodeStore.js";
import { InternalError, Logger } from "@matter/general";
import { FabricManager } from "@matter/protocol";
import { DescriptorServer } from "../../behaviors/descriptor/DescriptorServer.js";
const logger = Logger.get("BehaviorInit");
class ServerEndpointInitializer extends EndpointInitializer {
  #store;
  constructor(environment) {
    super();
    this.#store = environment.get(ServerNodeStore);
    this.variableService = new EndpointVariableService(environment);
  }
  initializeDescendant(endpoint) {
    if (!endpoint.lifecycle.hasId) {
      endpoint.id = this.#identifyPart(endpoint);
    }
    this.#store.endpointStores.assignNumber(endpoint);
    if (!(DescriptorServer.id in endpoint.behaviors.supported)) {
      endpoint.behaviors.inject(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 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 Endpoint)) {
      throw new InternalError("Cannot determine ID for endpoint with unknown parent type");
    }
    if (!endpoint.owner.lifecycle.hasId) {
      throw new InternalError("Cannot determine ID for endpoint because parent has no ID");
    }
    const index = endpoint.owner.parts.indexOf(endpoint);
    if (index === -1) {
      throw new 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(FabricManager)) {
      const fabricIndices = agent.env.get(FabricManager).fabrics.map((fabric) => fabric.fabricIndex);
      if (fabricIndices.length > 0) {
        return limitEndpointAttributeDataToAllowedFabrics(agent, fabricIndices);
      }
    }
  }
}
export {
  ServerEndpointInitializer
};
//# sourceMappingURL=ServerEndpointInitializer.js.map
