"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : /* @__PURE__ */ Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
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 __using = (stack, value, async) => {
  if (value != null) {
    if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
    var dispose, inner;
    if (async) dispose = value[__knownSymbol("asyncDispose")];
    if (dispose === void 0) {
      dispose = value[__knownSymbol("dispose")];
      if (async) inner = dispose;
    }
    if (typeof dispose !== "function") __typeError("Object not disposable");
    if (inner) dispose = function() {
      try {
        inner.call(this);
      } catch (e) {
        return Promise.reject(e);
      }
    };
    stack.push([async, dispose, value]);
  } else if (async) {
    stack.push([async]);
  }
  return value;
};
var __callDispose = (stack, error, hasError) => {
  var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
    return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
  };
  var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
  var next = (it) => {
    while (it = stack.pop()) {
      try {
        var result = it[1] && it[1].call(it[2]);
        if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
      } catch (e) {
        fail(e);
      }
    }
    if (hasError) throw error;
  };
  return next();
};
var MqttInterface_exports = {};
__export(MqttInterface_exports, {
  MqttInterface: () => MqttInterface
});
module.exports = __toCommonJS(MqttInterface_exports);
var import_StateStream = require("#node/integration/StateStream.js");
var import_general = require("@matter/general");
var import_model = require("@matter/model");
var import_types = require("@matter/types");
var import_Api = require("../remote/api/Api.js");
var import_ApiPath = require("../remote/api/ApiPath.js");
var import_Envelope = require("../remote/api/Envelope.js");
var import_RemoteResponse = require("../remote/api/RemoteResponse.js");
var import_RemoteInterface = require("../remote/RemoteInterface.js");
/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
const LOG_FACILITY = "MQTT";
class MqttInterface extends import_RemoteInterface.RemoteInterface {
  static protocol = "mqtt";
  #endpoint;
  #mutex = new import_general.Mutex(this);
  #retainedTopics = /* @__PURE__ */ new Map();
  async start() {
    this.#endpoint = await this.env.get(import_general.MqttService).connect({
      address: this.address,
      environment: this.node.env,
      certificate: this.certificate,
      key: this.key,
      will: {
        topic: this.root.at("status").toString(),
        payload: "offline"
      },
      onUp: (endpoint) => {
        if (!this.#endpoint) {
          this.#endpoint = endpoint;
        }
        return this.#publish({
          topic: this.root.at("status").toString(),
          payload: "online"
        });
      }
    });
    this.addWorker(this.#listen());
    this.addWorker(this.#feed());
  }
  async stop() {
    await this.#mutex.then();
    await this.#mqtt?.close();
  }
  /**
   * A background process that handles incoming MQTT messages.
   */
  async #listen() {
    var _stack = [];
    try {
      const _lifetime = __using(_stack, this.join("listening"));
      await import_general.Abort.race(this.abort, this.node.construction);
      if (import_general.Abort.is(this.abort)) {
        return;
      }
      let topic = this.root.toString();
      if (topic !== "") {
        topic += "/#";
      } else {
        topic = "#";
      }
      for await (const message of this.#mqtt.subscribe(`${topic}`, { noLocal: true, abort: this.abort })) {
        if (message.retain) {
          continue;
        }
        const relativeTopic = this.root.subpathFor(new import_ApiPath.ApiPath(message.topic));
        if (!relativeTopic) {
          continue;
        }
        await this.#respond(relativeTopic, message);
      }
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  async #respond(topic, message) {
    let response;
    const via = message.correlationData ? import_general.Bytes.toHex(message.correlationData) : message.responseTopic;
    try {
      await this.node.act("MQTT listener", async (agent) => {
        if (topic.toString() === "call") {
          response = await this.#call(message);
          return;
        }
        const resource = await import_Api.Api.resourceFor(agent, topic);
        if (resource === void 0) {
          throw new import_types.StatusResponse.NotFoundError(`No resource at subtopic ${topic}`);
        }
        const schema = resource.schema;
        if (!schema) {
          throw new import_general.NotImplementedError();
        }
        const input = payloadToJs(schema, message.payload);
        if (resource.isInvocable) {
          import_Api.Api.logRequest(LOG_FACILITY, via, "invoke", topic.toString());
          let value = await resource.invoke({ js: input });
          const responseSchema = schema.responseModel;
          if (responseSchema) {
            value ??= new import_Envelope.Envelope({ supervisor: resource.supervisorFor(responseSchema), js: null });
            response = { kind: "value", value };
          }
        } else {
          import_Api.Api.logRequest(LOG_FACILITY, via, "update", topic.toString());
          await resource.patch(input ?? { js: null });
        }
      });
    } catch (e) {
      response = import_Api.Api.errorResponseOf(LOG_FACILITY, via, e);
    }
    if (!response) {
      response = { kind: "ok" };
    }
    response.id = via;
    import_Api.Api.logResponse(LOG_FACILITY, (0, import_RemoteResponse.RemoteResponse)(response));
    if (message.responseTopic) {
      await this.#publish({
        topic: message.responseTopic,
        correlationData: message.correlationData,
        payload: (0, import_general.asJson)(response)
      });
    }
  }
  /**
   * Specialized handling for "call" topic to support full {@link RemoteRequest}/{@link RemoteResponse} interaction.
   */
  async #call(message) {
    const request = parseJsonPayload(message.payload);
    const response = await import_Api.Api.execute(LOG_FACILITY, this.node, request, this.abort);
    if (response.kind === "subscription") {
      await response.stream.return?.();
      throw new import_types.StatusResponse.InvalidSubscriptionError(
        "Subscription via RPC is not supported, use MQTT instead"
      );
    }
    return response;
  }
  /**
   * A background process that continuously updates MQTT topics.
   */
  async #feed() {
    var _stack = [];
    try {
      const _lifetime = __using(_stack, this.join("feeding"));
      const stream = (0, import_StateStream.StateStream)(this.node, { abort: this.abort });
      for await (const change of stream) {
        await this.#mutex.produce(async () => {
          switch (change.kind) {
            case "update":
              await this.#publishUpdate(change);
              break;
            case "delete":
              await this.#publishDelete(change);
          }
        });
      }
    } catch (_) {
      var _error = _, _hasError = true;
    } finally {
      __callDispose(_stack, _error, _hasError);
    }
  }
  /**
   * Publish attribute values for state changes.
   */
  async #publishUpdate({ node, endpoint, behavior, changes }) {
    let nodeTopics = this.#retainedTopics.get(node.id);
    if (nodeTopics === void 0) {
      this.#retainedTopics.set(node.id, nodeTopics = /* @__PURE__ */ new Map());
    }
    let endpointTopics = nodeTopics.get(endpoint.number);
    if (endpointTopics === void 0) {
      nodeTopics.set(endpoint.number, endpointTopics = /* @__PURE__ */ new Set());
    }
    const behaviorRoot = this.#nodeRoot(node.id).at([endpoint.number.toString(), (0, import_general.decamelize)(behavior.id)]);
    for (const name in changes) {
      const value = changes[name];
      const schema = behavior.schema.conformant.properties.for(name);
      const payload = jsToPayload(schema ?? import_model.any, value);
      const topic = behaviorRoot.at([name]).toString();
      endpointTopics.add(topic);
      await this.#publish({
        topic,
        payload,
        retain: true
      });
    }
  }
  /**
   * Delete all published topics for an endpoint or node that has disappeared.
   */
  async #publishDelete(change) {
    const nodeTopics = this.#retainedTopics.get(change.node.id);
    if (!nodeTopics) {
      return;
    }
    const deleteEndpoint = async (endpoint) => {
      const topics = nodeTopics.get(endpoint);
      if (!topics) {
        return;
      }
      for (const topic of topics) {
        await this.#publish({
          topic,
          payload: null,
          retain: true
        });
      }
      nodeTopics.delete(endpoint);
    };
    if (change.endpoint === change.node) {
      for (const number of nodeTopics.keys()) {
        await deleteEndpoint(number);
      }
      this.#retainedTopics.delete(change.node.id);
    } else {
      await deleteEndpoint(change.endpoint.number);
    }
  }
  /**
   * Obtain the root path for a node.
   *
   * This will either be the root path for the server or a subpath for peers.
   */
  #nodeRoot(id) {
    if (id === this.node.id) {
      return this.root;
    }
    return this.root.at(["peers", id]);
  }
  /**
   * Safe access to the MQTT endpoint.
   */
  get #mqtt() {
    if (this.#endpoint === void 0) {
      throw new import_general.InternalError("MQTT endpoint missing");
    }
    return this.#endpoint;
  }
  /**
   * Publish a message.
   *
   * Default QOS is 2.
   */
  #publish(message) {
    if (this.abort.aborted) {
      throw new import_general.InternalError("MQTT publish after abort");
    }
    if (message.qos === void 0) {
      message.qos = 2;
    }
    return this.#mqtt.publish(message);
  }
}
function payloadToJs(schema, payload) {
  if (payload === null) {
    return null;
  }
  const length = typeof payload === "string" ? payload.length : payload.byteLength;
  if (!length) {
    return null;
  }
  let js;
  switch (schema.effectiveMetatype) {
    case import_model.Metatype.any:
      js = payload;
      break;
    case import_model.Metatype.object:
    case import_model.Metatype.array:
    case import_model.Metatype.bitmap:
      js = parseJsonPayload(payload);
      break;
    case import_model.Metatype.bytes:
      if (typeof payload === "string") {
        try {
          js = import_general.Base64.decode(payload);
        } catch (e) {
          if (e instanceof SyntaxError) {
            throw new import_types.StatusResponse.InvalidDataTypeError(
              `Value is not binary or a base64 string: ${e.message}`
            );
          }
        }
        break;
      }
      js = payload;
      break;
    default:
      if (import_general.Bytes.isBytes(payload)) {
        try {
          payload = import_general.Bytes.toString(payload);
        } catch (e) {
          if (e instanceof TypeError) {
            throw new import_types.StatusResponse.InvalidDataTypeError(
              `Value is not a valid UTF-8 string: ${e.message}`
            );
          }
        }
      }
      js = payload;
      break;
  }
  return js;
}
function jsToPayload(schema, js) {
  if (js === void 0 || js === null || js === "") {
    return import_general.Bytes.empty;
  }
  switch (schema.effectiveMetatype) {
    case import_model.Metatype.object:
    case import_model.Metatype.array:
    case import_model.Metatype.bitmap:
      return (0, import_general.asJson)(js);
    case import_model.Metatype.bytes:
      if (import_general.Bytes.isBytes(js)) {
        return js;
      }
      return import_general.Bytes.fromString(js.toString());
    default:
      if (import_general.Bytes.isBytes(js)) {
        return js;
      }
      return js.toString();
  }
}
function parseJsonPayload(payload) {
  if (payload === null) {
    throw new import_types.StatusResponse.InvalidDataTypeError("Empty payload where JSON expected");
  }
  if (import_general.Bytes.isBytes(payload)) {
    payload = import_general.Bytes.toString(payload);
  }
  try {
    return JSON.parse(payload);
  } catch (e) {
    if (e instanceof SyntaxError) {
      throw new import_types.StatusResponse.InvalidDataTypeError(`Payload is not valid JSON: ${e.message}`);
    }
    throw e;
  }
}
//# sourceMappingURL=MqttInterface.js.map
