"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 SoftwareUpdateManager_exports = {};
__export(SoftwareUpdateManager_exports, {
  OtaUpdateStatus: () => OtaUpdateStatus,
  SoftwareUpdateManager: () => SoftwareUpdateManager
});
module.exports = __toCommonJS(SoftwareUpdateManager_exports);
var import_Behavior = require("#behavior/Behavior.js");
var import_DclBehavior = require("#behavior/system/dcl/DclBehavior.js");
var import_OtaAnnouncements = require("#behavior/system/software-update/OtaAnnouncements.js");
var import_basic_information = require("#behaviors/basic-information");
var import_Node = require("#node/Node.js");
var import_general = require("@matter/general");
var import_protocol = require("@matter/protocol");
var import_ota_software_update_requestor = require("@matter/types/clusters/ota-software-update-requestor");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const logger = import_general.Logger.get("SoftwareUpdateManager");
var OtaUpdateStatus = /* @__PURE__ */ ((OtaUpdateStatus2) => {
  OtaUpdateStatus2[OtaUpdateStatus2["Unknown"] = 0] = "Unknown";
  OtaUpdateStatus2[OtaUpdateStatus2["WaitForConsent"] = 1] = "WaitForConsent";
  OtaUpdateStatus2[OtaUpdateStatus2["Querying"] = 2] = "Querying";
  OtaUpdateStatus2[OtaUpdateStatus2["Downloading"] = 3] = "Downloading";
  OtaUpdateStatus2[OtaUpdateStatus2["WaitForApply"] = 4] = "WaitForApply";
  OtaUpdateStatus2[OtaUpdateStatus2["Applying"] = 5] = "Applying";
  OtaUpdateStatus2[OtaUpdateStatus2["Done"] = 6] = "Done";
  OtaUpdateStatus2[OtaUpdateStatus2["Cancelled"] = 7] = "Cancelled";
  return OtaUpdateStatus2;
})(OtaUpdateStatus || {});
class SoftwareUpdateManager extends import_Behavior.Behavior {
  static id = "softwareupdates";
  async initialize() {
    const rootNode = import_Node.Node.forEndpoint(this.endpoint);
    rootNode.behaviors.require(import_DclBehavior.DclBehavior);
    this.internal.otaService = rootNode.agentFor(this.context).get(import_DclBehavior.DclBehavior).otaUpdateService;
    await this.internal.otaService.construction;
    this.reactTo(rootNode.lifecycle.online, this.#nodeOnline);
    if (rootNode.lifecycle.isOnline) {
      await this.#nodeOnline();
    }
    this.reactTo(this.events.announceAsDefaultProvider$Changed, this.#updateAnnouncementSettings);
    this.reactTo(this.events.announcementInterval$Changed, this.#updateAnnouncementSettings);
  }
  async #nodeOnline() {
    if (this.internal.announcements !== void 0) {
      await this.internal.announcements.close();
      this.internal.announcements = void 0;
    }
    const fabricAuthority = this.env.get(import_protocol.FabricAuthority);
    const ownFabric = fabricAuthority.fabrics[0];
    if (!ownFabric) {
      logger.info(`No commissioned peers yet, cannot check for OTA updates. Wait for Fabric being added.`);
      this.reactTo(fabricAuthority.fabricAdded, this.#nodeOnline, { once: true });
      return;
    }
    this.internal.announcements = new import_OtaAnnouncements.OtaAnnouncements(this.endpoint, ownFabric);
    this.#updateAnnouncementSettings();
    const delay = (0, import_general.Millis)((0, import_general.Seconds)(Math.floor(Math.random() * 300)) + (0, import_general.Minutes)(5));
    logger.info(`Scheduling first OTA update check in ${import_general.Duration.format(delay)}`);
    this.internal.checkForUpdateTimer?.stop();
    this.internal.checkForUpdateTimer = import_general.Time.getTimer(
      "initializeUpdateCheck",
      delay,
      this.callback(this.#initializeUpdateCheck)
    ).start();
  }
  #updateAnnouncementSettings() {
    if (this.internal.announcements === void 0) {
      return;
    }
    if (this.state.announceAsDefaultProvider) {
      this.internal.announcements.interval = this.state.announcementInterval;
    } else {
      this.internal.announcements.interval = void 0;
    }
  }
  /**
   * Trigger the first check for updates some time after the node went online, and register a periodic interval
   * afterward.
   */
  async #initializeUpdateCheck() {
    try {
      await this.#checkAvailableUpdates();
    } catch (error) {
      logger.notice(`Error during initial OTA update check:`, error);
    }
    this.internal.checkForUpdateTimer.stop();
    this.internal.checkForUpdateTimer = import_general.Time.getPeriodicTimer(
      "checkAvailableUpdates",
      this.state.updateCheckInterval,
      this.callback(this.#checkAvailableUpdates)
    ).start();
  }
  get storage() {
    return this.internal.otaService.storage;
  }
  get #rebootResubscribeArmer() {
    if (this.internal.rebootResubscribeArmer === void 0) {
      this.internal.rebootResubscribeArmer = new import_protocol.RebootResubscribeArmer(
        this.env.get(import_protocol.SessionManager),
        this.env.get(import_protocol.ClientSubscriptions)
      );
    }
    return this.internal.rebootResubscribeArmer;
  }
  /**
   * Returns a snapshot of the current update queue for introspection.
   */
  get queuedUpdates() {
    const now = import_general.Time.nowMs;
    return this.internal.updateQueue.map((entry) => {
      let status;
      if (entry.lastProgressUpdateTime === void 0) {
        status = "queued";
      } else if (entry.lastProgressUpdateTime + (0, import_general.Minutes)(15) < now) {
        status = "stalled";
      } else {
        status = "in-progress";
      }
      return {
        peerAddress: entry.peerAddress,
        vendorId: entry.vendorId,
        productId: entry.productId,
        targetSoftwareVersion: entry.targetSoftwareVersion,
        status,
        lastProgressStatus: entry.lastProgressStatus,
        lastProgressUpdateTime: entry.lastProgressUpdateTime
      };
    });
  }
  /** Validate that we know the peer the update is requested for and the details match to what we know */
  async #validatePeerDetails(peerAddress, details) {
    const { softwareVersion, vendorId, productId } = details;
    const peers = import_Node.Node.forEndpoint(this.endpoint).peers;
    const node = peers.get(peerAddress);
    const basicInfo = node?.maybeStateOf(import_basic_information.BasicInformationClient);
    if (basicInfo?.softwareVersion === softwareVersion && basicInfo?.vendorId === vendorId && basicInfo?.productId === productId) {
      return true;
    }
    return false;
  }
  /**
   * Used to determine if an update is existing in our storage for a peer with a certain software version.
   *
   * It uses the already checked details and does not check again on-demand. It considers consents already given,
   * but validates the peer data.
   */
  async updateExistsFor(peerAddress, { softwareVersion, vendorId, productId, requestorCanConsent }) {
    if (!await this.#validatePeerDetails(peerAddress, { softwareVersion, vendorId, productId })) {
      logger.info(
        `Peer details for node ${peerAddress.toString()} do not match values the update was requested for, ignoring`
      );
      return void 0;
    }
    const availableUpdates = await this.internal.otaService.find({ vendorId, productId });
    const candidates = availableUpdates.filter(
      ({
        softwareVersion: candidateSoftwareVersion,
        minApplicableSoftwareVersion = 0,
        maxApplicableSoftwareVersion = softwareVersion,
        mode
      }) => softwareVersion < candidateSoftwareVersion && softwareVersion >= minApplicableSoftwareVersion && softwareVersion <= maxApplicableSoftwareVersion && (mode === "prod" || this.state.allowTestOtaImages)
    ).sort((a, b) => b.softwareVersion - a.softwareVersion);
    if (candidates.length === 0) {
      return void 0;
    }
    const candidatesWithConsent = candidates.map((candidate2) => {
      const consent = this.internal.consents.filter((consent2) => consent2.vendorId === candidate2.vendorId && consent2.productId === candidate2.productId).filter((consent2) => consent2.targetSoftwareVersion >= candidate2.softwareVersion);
      return {
        ...candidate2,
        consentPeers: consent.map((c) => c.peerAddress)
      };
    });
    let candidate;
    let consentRequired = false;
    if (requestorCanConsent) {
      candidate = candidatesWithConsent[0];
      consentRequired = !candidate.consentPeers.some(
        ({ fabricIndex, nodeId }) => fabricIndex === peerAddress.fabricIndex && nodeId === peerAddress.nodeId
      );
    } else {
      candidate = candidatesWithConsent.find(
        ({ consentPeers }) => consentPeers.some(
          ({ fabricIndex, nodeId }) => fabricIndex === peerAddress.fabricIndex && nodeId === peerAddress.nodeId
        )
      );
    }
    if (candidate) {
      const { softwareVersion: softwareVersion2, softwareVersionString, filename } = candidate;
      return {
        newSoftwareVersion: softwareVersion2,
        newSoftwareVersionString: softwareVersionString,
        fileDesignator: new import_protocol.FileDesignator(`ota/${filename}`),
        // We do not provide any httpsUri here, as we expect the node to download from our DCL proxy via BDX
        consentRequired
      };
    } else {
      logger.info(
        `No update candidate found for node ${peerAddress.nodeId} in fabric ${peerAddress.fabricIndex} for any update`
      );
    }
  }
  /** Triggered by a Timer to call the update with different parameters */
  async #checkAvailableUpdates() {
    await this.queryUpdates({ includeStoredUpdates: true });
    await this.#cleanupObsoleteUpdates();
  }
  /**
   * Clean up stored OTA files that no node in the system needs anymore.
   * A stored version is obsolete when ALL nodes with that vendor/product ID are already at or above that version,
   * or when its mode is no longer permitted by the current settings (e.g. test-mode files after
   * {@link allowTestOtaImages} is turned off). Only cleans "prod" and "test" mode files;
   * "local" files are user-managed.
   */
  async #cleanupObsoleteUpdates() {
    const rootNode = import_Node.Node.forEndpoint(this.endpoint);
    const nodeVersions = /* @__PURE__ */ new Map();
    for (const peer of rootNode.peers) {
      const basicInfo = peer.maybeStateOf(import_basic_information.BasicInformationClient);
      if (basicInfo === void 0) {
        continue;
      }
      const { vendorId, productId, softwareVersion } = basicInfo;
      const key = `${vendorId}-${productId}`;
      const existing = nodeVersions.get(key);
      if (existing === void 0 || softwareVersion < existing) {
        nodeVersions.set(key, softwareVersion);
      }
    }
    const purgeDisallowedTestFiles = !this.state.allowTestOtaImages;
    if (nodeVersions.size === 0 && !purgeDisallowedTestFiles) {
      return;
    }
    const storedUpdates = await this.internal.otaService.find(nodeVersions.size === 0 ? { mode: "test" } : {});
    for (const update of storedUpdates) {
      if (update.mode === "local") {
        continue;
      }
      if (update.mode === "test" && purgeDisallowedTestFiles) {
        try {
          await this.internal.otaService.delete({ filename: update.filename });
          logger.info(`Cleaned up test-mode OTA file ${update.filename} (allowTestOtaImages is disabled)`);
        } catch (error) {
          logger.warn(`Failed to clean up OTA file ${update.filename}:`, error);
        }
        continue;
      }
      if (nodeVersions.size === 0) {
        continue;
      }
      const key = `${update.vendorId}-${update.productId}`;
      const minNodeVersion = nodeVersions.get(key);
      if (minNodeVersion === void 0) {
        continue;
      }
      if (update.softwareVersion <= minNodeVersion) {
        try {
          await this.internal.otaService.delete({ filename: update.filename });
          logger.info(
            `Cleaned up obsolete OTA file ${update.filename} (all nodes at version >= ${minNodeVersion})`
          );
        } catch (error) {
          logger.warn(`Failed to clean up OTA file ${update.filename}:`, error);
        }
      }
    }
  }
  /**
   * Checks all nodes, or optionally a defined one, for available updates from the DCL OTA Update Service.
   *
   * Returns a list of peers for which updates are available along with the collected update info.
   *
   * If `includeStoredUpdates` is set to true, locally stored/imported OTA images are considered as update candidates
   * alongside the DCL. The DCL is always queried regardless; across all candidates the highest applicable and allowed
   * version wins.
   */
  async queryUpdates(options = {}) {
    const { peerToCheck, includeStoredUpdates = false } = options;
    const rootNode = import_Node.Node.forEndpoint(this.endpoint);
    const updateDetails = /* @__PURE__ */ new Map();
    for (const peer of rootNode.peers) {
      if (this.internal.closed) {
        return [];
      }
      if (peerToCheck !== void 0 && peerToCheck !== peer) {
        continue;
      }
      const details = this.#preparePeerForUpdate(peer);
      if (details === void 0) {
        continue;
      }
      const { otaEndpoint, peerAddress, vendorId, productId, softwareVersion, softwareVersionString } = details;
      const key = `${vendorId}-${productId}-${softwareVersion}`;
      const versionData = updateDetails.get(key) ?? {
        vendorId,
        productId,
        softwareVersion,
        softwareVersionString,
        otaEndpoints: /* @__PURE__ */ new Set()
      };
      versionData.otaEndpoints.add({ endpoint: otaEndpoint, peerAddress });
      updateDetails.set(key, versionData);
    }
    if (updateDetails.size === 0) {
      logger.info(`No updatable nodes found`);
      return [];
    }
    const peersWithUpdates = new Array();
    for (const infos of updateDetails.values()) {
      if (this.internal.closed) {
        return [];
      }
      try {
        const peers = await this.#checkProductForUpdates(infos, includeStoredUpdates);
        for (const peer of peers) {
          const info = this.internal.knownUpdates.get(peer);
          if (info === void 0) {
            continue;
          }
          peersWithUpdates.push({ peerAddress: peer, info });
        }
      } catch (error) {
        logger.warn(
          `Error while checking for updates for product ${infos.vendorId}-${infos.productId}:`,
          error
        );
      }
    }
    return peersWithUpdates;
  }
  /**
   * Check storage and DCL for updates for the given product/version, downloads it, and notify nodes if an update was
   * found
   */
  async #checkProductForUpdates(infos, includeStoredUpdates) {
    const { vendorId, productId, softwareVersion, otaEndpoints } = infos;
    const updateDetails = await this.internal.otaService.checkForUpdate({
      vendorId,
      productId,
      currentSoftwareVersion: softwareVersion,
      includeStoredUpdates,
      isProduction: this.state.allowTestOtaImages ? void 0 : true
    });
    if (!updateDetails || this.internal.closed) {
      return [];
    }
    const fd = await this.internal.otaService.downloadUpdate(updateDetails);
    logger.info(
      "OTA update available for",
      import_general.Diagnostic.dict({
        vendorId,
        productId,
        softwareVersion,
        file: fd.text,
        peers: [...otaEndpoints.values()].map(({ peerAddress }) => peerAddress.toString())
      })
    );
    for (const { endpoint, peerAddress } of otaEndpoints) {
      const { vid, pid, softwareVersion: softwareVersion2, softwareVersionString, releaseNotesUrl, specificationVersion, source } = updateDetails;
      const details = {
        vendorId: vid,
        productId: pid,
        softwareVersion: softwareVersion2,
        softwareVersionString,
        releaseNotesUrl,
        specificationVersion,
        source
      };
      this.internal.knownUpdates.set(peerAddress, details);
      const hasConsent = this.internal.consents.some(
        (consent) => consent.vendorId === vendorId && consent.productId === productId && consent.targetSoftwareVersion === updateDetails.softwareVersion && consent.peerAddress.fabricIndex === peerAddress.fabricIndex && consent.peerAddress.nodeId === peerAddress.nodeId
      );
      if (this.internal.closed) {
        break;
      }
      if (hasConsent) {
        this.#queueUpdate({
          endpoint,
          vendorId,
          productId,
          targetSoftwareVersion: updateDetails.softwareVersion,
          peerAddress
        });
      } else {
        this.requestConsentForUpdate(peerAddress, details);
      }
    }
    return [...otaEndpoints.values()].map(({ peerAddress }) => peerAddress);
  }
  /**
   * Determine if we can request an update for the given node and return node meta-data needed for the process.
   * The Node needs to be commissioned (have a peer address), being not disabled, and having an active subscription
   * (to not work with outdated data).
   * When a node is applicable for updates, it also subscribes to softwareVersion changes to be able to react
   */
  #preparePeerForUpdate(peer) {
    const otaData = this.internal.announcements?.peerApplicableForUpdate(peer);
    if (otaData === void 0) {
      return;
    }
    const { peerAddress, otaEndpoint } = otaData;
    const { vendorId, productId, softwareVersion, softwareVersionString } = peer.stateOf(import_basic_information.BasicInformationClient);
    const versionEvent = peer.eventsOf(import_basic_information.BasicInformationClient).softwareVersion$Changed;
    if (!this.internal.versionUpdateObservers.observes(versionEvent)) {
      let triggerVersionChange2 = function(newVersion) {
        that.#onSoftwareVersionChanged(peerAddress, newVersion);
      };
      var triggerVersionChange = triggerVersionChange2;
      const that = this;
      this.internal.versionUpdateObservers.on(versionEvent, this.callback(triggerVersionChange2));
    }
    const startUpEvent = peer.eventsOf(import_basic_information.BasicInformationClient).startUp;
    if (!this.internal.versionUpdateObservers.observes(startUpEvent)) {
      let triggerStartUp2 = function({ softwareVersion: softwareVersion2 }, context) {
        that.#onSoftwareVersionChanged(
          peerAddress,
          softwareVersion2,
          true,
          (0, import_protocol.hasRemoteActor)(context) ? context.session : void 0
        );
      };
      var triggerStartUp = triggerStartUp2;
      const that = this;
      this.internal.versionUpdateObservers.on(startUpEvent, this.callback(triggerStartUp2));
    }
    return { otaEndpoint, peerAddress, vendorId, productId, softwareVersion, softwareVersionString };
  }
  /**
   * Handler for softwareVersion changes on a peer.
   *
   * Also called from the startUp event with `isStartUp = true`. When a device reboots after applying an update,
   * softwareVersion$Changed fires if the version actually changed (success). But if the device reboots with the
   * same version (failed apply), softwareVersion$Changed does NOT fire — so startUp feeds the version through
   * this same handler to detect the failure.
   */
  #onSoftwareVersionChanged(peerAddress, newVersion, isStartUp = false, currentSession) {
    const entryIndex = this.internal.updateQueue.findIndex(
      (e) => e.peerAddress.fabricIndex === peerAddress.fabricIndex && e.peerAddress.nodeId === peerAddress.nodeId
    );
    if (isStartUp) {
      const suppressedSessionId = this.internal.pendingStartUpSuppress.get(peerAddress);
      if (suppressedSessionId !== void 0) {
        this.internal.pendingStartUpSuppress.delete(peerAddress);
        const sessionId = currentSession?.id ?? this.env.get(import_protocol.SessionManager).maybeSessionFor(peerAddress)?.id;
        if (sessionId === suppressedSessionId) {
          return;
        }
      }
    }
    if (entryIndex === -1) {
      return;
    }
    const entry = this.internal.updateQueue[entryIndex];
    const previousProgressStatus = entry.lastProgressStatus;
    if (entry.lastProgressUpdateTime !== void 0) {
      logger.info(
        `Clearing in-progress update for node ${peerAddress.toString()} due to software version change. Last State was ${OtaUpdateStatus[entry.lastProgressStatus]}`
      );
      entry.lastProgressUpdateTime = void 0;
      entry.lastProgressStatus = 0 /* Unknown */;
    }
    const expectedVersion = entry.targetSoftwareVersion;
    if (newVersion < expectedVersion) {
      if (isStartUp && (previousProgressStatus === 5 /* Applying */ || previousProgressStatus === 4 /* WaitForApply */)) {
        logger.warn(
          `Device ${peerAddress.toString()} rebooted after applying update but reports softwareVersion ${newVersion} (expected >= ${expectedVersion}), update failed to apply`
        );
        this.internal.updateQueue.splice(entryIndex, 1);
        this.internal.pendingStartUpSuppress.delete(peerAddress);
        this.events.updateFailed.emit(peerAddress);
        this.#triggerQueuedUpdate();
        return;
      }
      logger.info(
        `Software version for node ${peerAddress.toString()} changed to ${newVersion}, but still below target version ${expectedVersion}, keeping in update queue`
      );
      return;
    }
    logger.info(
      `Software version changed to ${newVersion} (expected ${expectedVersion}) for node ${peerAddress.toString()}, removing from update queue`
    );
    this.internal.knownUpdates.delete(peerAddress);
    this.internal.pendingStartUpSuppress.delete(peerAddress);
    this.events.updateDone.emit(peerAddress);
    this.internal.updateQueue.splice(entryIndex, 1);
    this.internal.consents = this.internal.consents.filter(
      ({ peerAddress: consentAddress, targetSoftwareVersion }) => !import_protocol.PeerAddress.is(peerAddress, consentAddress) || targetSoftwareVersion > newVersion
    );
    this.#triggerQueuedUpdate();
  }
  /**
   * Notify the application that consent is needed for the given update on the given peer
   */
  requestConsentForUpdate(peerAddress, updateDetails) {
    this.events.updateAvailable.emit(peerAddress, updateDetails);
  }
  /**
   * Add an update to the update queue and execute it.
   */
  #queueUpdate(entry) {
    const existing = this.internal.updateQueue.find(
      (e) => e.peerAddress.fabricIndex === entry.peerAddress.fabricIndex && e.peerAddress.nodeId === entry.peerAddress.nodeId
    );
    if (existing !== void 0) {
      if (existing.lastProgressUpdateTime !== void 0) {
        logger.info(
          `Update for node ${entry.peerAddress.toString()} already in progress, skipping queue update`
        );
        return;
      }
      existing.vendorId = entry.vendorId;
      existing.productId = entry.productId;
      existing.targetSoftwareVersion = entry.targetSoftwareVersion;
      existing.endpoint = entry.endpoint;
      logger.info(`Updated existing queued update for node ${entry.peerAddress.toString()}`);
    } else {
      logger.info(`Queuing update consent for node ${entry.peerAddress.toString()}`);
      this.internal.updateQueue.push(entry);
    }
    this.#triggerQueuedUpdate();
  }
  /**
   * Triggers updates for queued entries in the update queue, ensuring proper prioritization and handling of stalled
   * updates. This method checks for ongoing updates, resets states for stalled updates, and processes the next entry
   * in the queue if no update is currently in progress.
   *
   * The queue is re-sorted to prioritize entries with an unknown status, and a periodic timer is activated to
   * monitor for stalled updates.
   */
  #triggerQueuedUpdate() {
    if (this.internal.closed) {
      return;
    }
    const now = import_general.Time.nowMs;
    const inProgressEntries = this.internal.updateQueue.filter(
      ({ lastProgressUpdateTime }) => lastProgressUpdateTime !== void 0
    );
    let inProgressCount = inProgressEntries.length;
    if (inProgressCount === 0 && this.internal.updateQueueTimer?.isRunning) {
      this.internal.updateQueueTimer.stop();
    } else if (inProgressCount > 0) {
      for (const entry of inProgressEntries) {
        if (entry.lastProgressUpdateTime + (0, import_general.Minutes)(15) < now) {
          logger.info(
            `Resetting stalled OTA update state for node ${entry.peerAddress.toString()} due to inactivity`
          );
          entry.lastProgressUpdateTime = void 0;
          entry.lastProgressStatus = 0 /* Unknown */;
          inProgressCount--;
        }
      }
    }
    if (inProgressCount > 0) {
      return;
    }
    this.internal.updateQueue = this.internal.updateQueue.sort((a, b) => {
      const aStatus = a.lastProgressStatus === 0 /* Unknown */ ? 1 : 0;
      const bStatus = b.lastProgressStatus === 0 /* Unknown */ ? 1 : 0;
      return aStatus - bStatus;
    });
    const nextEntry = this.internal.updateQueue[0];
    if (nextEntry) {
      this.#triggerUpdateOnNode(nextEntry).catch((error) => {
        logger.warn(`Error while triggering OTA update on node ${nextEntry.peerAddress.toString()}:`, error);
      });
      if (!this.internal.updateQueueTimer?.isRunning) {
        this.internal.updateQueueTimer = import_general.Time.getPeriodicTimer(
          "checkQueuedUpdates",
          (0, import_general.Minutes)(5),
          this.callback(this.#triggerQueuedUpdate)
        ).start();
      }
    }
  }
  /**
   * Triggers an update on the given node. This method announces ourselves as OTA Provider to the node with an
   * available update and then triggers the update on the node.
   * The node usually calls queryImage as a result of this when it processes the announcement.
   */
  async #triggerUpdateOnNode(entry) {
    if (this.internal.announcements == void 0) {
      logger.info(`Not yet initialized with peers, can not trigger update on node`, entry.peerAddress);
      return;
    }
    const { endpoint, peerAddress } = entry;
    if (this.env.get(import_protocol.BdxProtocol).sessionFor(peerAddress, this.storage.scope) !== void 0) {
      logger.info(`BDX transfer still active for node ${peerAddress.toString()}, skipping announcement`);
      return;
    }
    try {
      logger.info(`Announcing OTA provider to node ${peerAddress.toString()}`);
      await this.internal.announcements.announceOtaProvider(
        endpoint,
        peerAddress,
        import_ota_software_update_requestor.OtaSoftwareUpdateRequestor.AnnouncementReason.UpdateAvailable
      );
      if (this.internal.updateQueue.indexOf(entry) >= 0) {
        entry.lastProgressUpdateTime = import_general.Time.nowMs;
      }
    } catch (error) {
      logger.warn(`Failed to announce OTA provider to node ${peerAddress.toString()}:`, error);
      entry.lastProgressUpdateTime = void 0;
      entry.lastProgressStatus = 0 /* Unknown */;
      this.#triggerQueuedUpdate();
    }
  }
  /**
   * Forces an OTA update for a specific node identified by its peer address, vendor ID, product ID,
   * and target software version. This method will override any ongoing updates by explicitly adding an update
   * consent for the specified node and processing the update immediately if applicable.
   * This can be used when an exact timing of the update is needed. When the update can be executed in a delayed/queued
   * manner, please use `addUpdateConsent()`.
   */
  async forceUpdate(peerAddress, vendorId, productId, targetSoftwareVersion) {
    peerAddress = (0, import_protocol.PeerAddress)(peerAddress);
    const existingEntry = this.internal.updateQueue.find(
      (e) => e.peerAddress.fabricIndex === peerAddress.fabricIndex && e.peerAddress.nodeId === peerAddress.nodeId && e.lastProgressUpdateTime !== void 0
    );
    if (existingEntry !== void 0) {
      const bdxProtocol = this.env.get(import_protocol.BdxProtocol);
      const activeSession = bdxProtocol.sessionFor(peerAddress, this.storage.scope);
      if (activeSession !== void 0) {
        logger.info(
          `Force update for node ${peerAddress.toString()} skipped: BDX transfer is actively in progress`
        );
        return;
      }
      logger.info(`Cleaning up stale update entry for node ${peerAddress.toString()} before forcing new update`);
      const staleIndex = this.internal.updateQueue.indexOf(existingEntry);
      if (staleIndex >= 0) {
        this.internal.updateQueue.splice(staleIndex, 1);
        this.internal.pendingStartUpSuppress.delete(peerAddress);
      }
      try {
        await bdxProtocol.disablePeerForScope(peerAddress, this.storage, true);
      } catch (error) {
        import_general.MatterError.accept(error);
        logger.debug(`Error cleaning up stale BDX registration:`, error);
      }
    }
    const added = await this.addUpdateConsent(peerAddress, vendorId, productId, targetSoftwareVersion);
    if (!added) {
      throw new import_protocol.OtaUpdateError(`Node at ${peerAddress.toString()} is not currently applicable for OTA updates`);
    }
    const entry = this.internal.updateQueue.find(
      (e) => e.peerAddress.fabricIndex === peerAddress.fabricIndex && e.peerAddress.nodeId === peerAddress.nodeId && e.vendorId === vendorId && e.productId === productId && e.targetSoftwareVersion === targetSoftwareVersion
    );
    if (!entry) {
      throw new import_general.InternalError(`Failed to find queued update after adding consent`);
    }
    if (this.internal.updateQueue.length === 1) {
      return;
    }
    await this.#triggerUpdateOnNode(entry);
  }
  /** Tries to cancel an ongoing OTA update for the given peer address. */
  async #cancelUpdate(peerAddress) {
    peerAddress = (0, import_protocol.PeerAddress)(peerAddress);
    const bdxProtocol = this.env.get(import_protocol.BdxProtocol);
    await bdxProtocol.disablePeerForScope(peerAddress, this.storage, true);
    const entryIndex = this.internal.updateQueue.findIndex(
      (e) => e.peerAddress.fabricIndex === peerAddress.fabricIndex && e.peerAddress.nodeId === peerAddress.nodeId
    );
    if (entryIndex < 0) {
      logger.warn(`No Ota update queued for node ${peerAddress.toString()}`);
      return;
    }
    const entry = this.internal.updateQueue[entryIndex];
    if (entry.lastProgressStatus === 5 /* Applying */ || entry.lastProgressStatus === 6 /* Done */) {
      logger.info(`Cannot cancel update for node ${peerAddress.toString()}, already applying or done`);
      return;
    }
    this.internal.updateQueue.splice(entryIndex, 1);
    this.internal.rebootResubscribeArmer?.disarm(peerAddress);
    this.internal.pendingStartUpSuppress.delete(peerAddress);
    logger.info(`Cancelled OTA update for node ${peerAddress.toString()}`);
    this.events.updateFailed.emit(peerAddress);
    this.#triggerQueuedUpdate();
  }
  /**
   * Adds or updates a consent for a given peer address, vendor ID, product ID, and target software version.
   * Filters out existing consents for the given peer address and replaces them with the new one.
   * If the node associated with the peer address is applicable for an update, it schedules the update to happen with
   * the next queue slot, so potentially delayed.
   * This can be used when the update can be executed in a delayed/queued manner and it does not matter exactly when.
   */
  async addUpdateConsent(peerAddress, vendorId, productId, targetSoftwareVersion) {
    peerAddress = (0, import_protocol.PeerAddress)(peerAddress);
    const consents = this.internal.consents.filter(
      (consent) => consent.peerAddress.fabricIndex !== peerAddress.fabricIndex || consent.peerAddress.nodeId !== peerAddress.nodeId
    );
    const node = await import_Node.Node.forEndpoint(this.endpoint).peers.forAddress(peerAddress);
    const {
      otaEndpoint,
      vendorId: nodeVendorId,
      productId: nodeProductId
    } = this.#preparePeerForUpdate(node) ?? {};
    if (otaEndpoint !== void 0 && (nodeVendorId !== vendorId || nodeProductId !== productId)) {
      throw new import_general.ImplementationError(`Node at ${peerAddress.toString()} does not match given vendorId/productId`);
    }
    consents.push({
      vendorId,
      productId,
      targetSoftwareVersion,
      peerAddress
    });
    this.internal.consents = consents;
    if (otaEndpoint === void 0) {
      logger.info(`Node ${peerAddress.toString()} is currently not applicable for OTA updates, try again later`);
      return false;
    }
    this.#queueUpdate({ vendorId, productId, targetSoftwareVersion, peerAddress, endpoint: otaEndpoint });
    return true;
  }
  /**
   * Checks if consent exists for the given peer address and optionally for a specific target software version.
   */
  hasConsent(peerAddress, targetSoftwareVersion) {
    return this.internal.consents.some(
      (consent) => consent.peerAddress.fabricIndex === peerAddress.fabricIndex && consent.peerAddress.nodeId === peerAddress.nodeId && (targetSoftwareVersion === void 0 || consent.targetSoftwareVersion === targetSoftwareVersion)
    );
  }
  /**
   * Checks for consent and removes it if present, also cancels if in progress. Use this to remove a formerly given
   * consent.
   */
  removeConsent(peerAddress, targetSoftwareVersion) {
    const consentIndex = this.internal.consents.findIndex(
      (consent) => consent.peerAddress.fabricIndex === peerAddress.fabricIndex && consent.peerAddress.nodeId === peerAddress.nodeId && (targetSoftwareVersion === void 0 || consent.targetSoftwareVersion === targetSoftwareVersion)
    );
    if (consentIndex >= 0) {
      this.internal.consents.splice(consentIndex, 1);
    } else {
      logger.info(
        `No consent to remove found for node ${peerAddress.toString()}${targetSoftwareVersion !== void 0 ? ` for version ${targetSoftwareVersion}` : ""}`
      );
    }
    return this.#cancelUpdate(peerAddress);
  }
  /**
   * Suppress the next startUp event from the given peer on the given session.
   * Called by OtaSoftwareUpdateProviderServer when a queryImage is detected as a post-reboot query
   * so the startUp event that follows is not treated as a new failure-after-apply.
   */
  suppressNextStartUp(peerAddress, sessionId) {
    this.internal.pendingStartUpSuppress.set(peerAddress, sessionId);
  }
  /**
   * Handles the status change of an OTA update for a given peer device.
   *
   * This method processes OTA update status notifications received from a specified device.
   * Based on the status, it updates the internal state of the update queue, logs relevant
   * messages, and triggers the necessary events.
   */
  onOtaStatusChange(peerAddress, status, toVersion) {
    if (this.internal.closed) {
      return;
    }
    peerAddress = (0, import_protocol.PeerAddress)(peerAddress);
    const entryIndex = this.internal.updateQueue.findIndex(
      (e) => e.peerAddress.fabricIndex === peerAddress.fabricIndex && e.peerAddress.nodeId === peerAddress.nodeId
    );
    if (entryIndex < 0) {
      if (status !== 7 /* Cancelled */) {
        logger.warn(
          `Received OTA status update from unknown node ${peerAddress.toString()}, status=${OtaUpdateStatus[status]}`
        );
      }
      return;
    }
    const entry = this.internal.updateQueue[entryIndex];
    if (status === 6 /* Done */) {
      logger.info(`OTA update completed for node`, peerAddress.toString());
      const completedVersion = toVersion ?? entry.targetSoftwareVersion;
      this.internal.updateQueue.splice(entryIndex, 1);
      this.internal.knownUpdates.delete(peerAddress);
      this.internal.pendingStartUpSuppress.delete(peerAddress);
      this.events.updateDone.emit(peerAddress);
      this.internal.consents = this.internal.consents.filter(
        ({ peerAddress: consentAddress, targetSoftwareVersion }) => !import_protocol.PeerAddress.is(peerAddress, consentAddress) || targetSoftwareVersion > completedVersion
      );
      this.#triggerQueuedUpdate();
    } else if (status === 7 /* Cancelled */) {
      logger.info(`OTA update BDX cancelled for node ${peerAddress.toString()}, resetting for retry`);
      this.internal.rebootResubscribeArmer?.disarm(peerAddress);
      entry.lastProgressUpdateTime = void 0;
      entry.lastProgressStatus = 0 /* Unknown */;
      this.#triggerQueuedUpdate();
    } else {
      logger.info(
        `OTA update status for node ${peerAddress.toString()} changed to ${OtaUpdateStatus[status]}${toVersion !== void 0 ? ` for version ${toVersion}` : ""}`
      );
      entry.lastProgressUpdateTime = import_general.Time.nowMs;
      entry.lastProgressStatus = status;
      if (status === 5 /* Applying */) {
        this.#rebootResubscribeArmer.arm(peerAddress);
      }
    }
  }
  async [Symbol.asyncDispose]() {
    this.internal.closed = true;
    this.internal.checkForUpdateTimer?.stop();
    this.internal.updateQueueTimer?.stop();
    await this.internal.announcements?.close();
    this.internal.versionUpdateObservers.close();
    this.internal.rebootResubscribeArmer?.[Symbol.dispose]();
    await super[Symbol.asyncDispose]?.();
  }
}
((SoftwareUpdateManager2) => {
  class State {
    /** Set this to true to also allow updates from the Test DCL */
    allowTestOtaImages = false;
    /** Default Update check Interval */
    updateCheckInterval = (0, import_general.Hours)(24);
    /** Announce this controller as Update provider to all nodes */
    announceAsDefaultProvider = false;
    /** Interval to Announces this controller as Update provider. Must not be lower than 24h! */
    announcementInterval = (0, import_general.Hours)(24);
  }
  SoftwareUpdateManager2.State = State;
  class Internal {
    /** Use this to pre-initialize consent to allow nodes to update automatically. The content will not be persisted! */
    consents = new Array();
    otaService;
    checkForUpdateTimer;
    updateQueue = new Array();
    updateQueueTimer;
    announcements;
    versionUpdateObservers = new import_general.ObserverGroup();
    knownUpdates = new import_protocol.PeerAddressMap();
    /**
     * Peer → session ID on which the reboot-triggering queryImage was received.
     *
     * Intentionally ephemeral (not persisted): the suppress window is sub-second — between the
     * queryImage response and the subsequent startUp event that follows on the same session.
     * Entries are consumed immediately when the matching startUp fires in #onSoftwareVersionChanged,
     * or cleaned up in #cancelUpdate when the peer is permanently removed from tracking.
     */
    pendingStartUpSuppress = new import_protocol.PeerAddressMap();
    rebootResubscribeArmer;
    closed = false;
  }
  SoftwareUpdateManager2.Internal = Internal;
  class Events extends import_general.EventEmitter {
    /** Emitted when an update is available for a Peer and there is no consent stored and contains update details */
    updateAvailable = (0, import_general.Observable)();
    /** Emitted when an update for a Peer is finished */
    updateDone = (0, import_general.Observable)();
    /** Emitted when an update for a Peer has failed or was cancelled */
    updateFailed = (0, import_general.Observable)();
    announceAsDefaultProvider$Changed = (0, import_general.Observable)();
    announcementInterval$Changed = (0, import_general.Observable)();
  }
  SoftwareUpdateManager2.Events = Events;
})(SoftwareUpdateManager || (SoftwareUpdateManager = {}));
//# sourceMappingURL=SoftwareUpdateManager.js.map
