/**
 * @license
 * Copyright 2025-2026 Open Home Foundation
 * SPDX-License-Identifier: Apache-2.0
 */
import { FabricId, Logger } from "@matter/main";
import { access, rename } from "node:fs/promises";
import { join } from "node:path";
const logger = Logger.get("ServerIdResolver");
const DEFAULT_SERVER_ID = "server";
function computeServerId(fabricId, vendorId) {
  return `server-${FabricId(fabricId).toString(16)}-${vendorId.toString(16)}`;
}
async function storageExists(storagePath, serverId) {
  if (storagePath === void 0) {
    return false;
  }
  try {
    const fullPath = join(storagePath, serverId);
    await access(fullPath);
    return true;
  } catch {
    return false;
  }
}
async function resolveServerId(env, config, options, vendorId, fabricId) {
  const requestedServerId = options.serverId ?? DEFAULT_SERVER_ID;
  if (requestedServerId !== DEFAULT_SERVER_ID) {
    logger.info(`Using provided server ID: ${requestedServerId}`);
    return requestedServerId;
  }
  if (vendorId === void 0 || fabricId === void 0) {
    logger.info(`Using default server ID (no fabric config): ${DEFAULT_SERVER_ID}`);
    return DEFAULT_SERVER_ID;
  }
  const storagePath = env.vars.get("storage.path");
  const candidateId = computeServerId(fabricId, vendorId);
  if (await storageExists(storagePath, candidateId)) {
    logger.info(`Found existing storage for server ID: ${candidateId}`);
    return candidateId;
  }
  if (await storageExists(storagePath, DEFAULT_SERVER_ID)) {
    try {
      const baseStorage = await config.service.open(DEFAULT_SERVER_ID);
      let closed = false;
      try {
        const fabricsContext = baseStorage.createContext("fabrics");
        const fabrics = await fabricsContext.get(
          "fabrics",
          []
        );
        if (fabrics.length === 1) {
          const fabricData = fabrics[0];
          const storedFabricId = fabricData.fabricId;
          const storedVendorId = fabricData.rootVendorId;
          if (storedFabricId === FabricId(fabricId) && storedVendorId === vendorId) {
            await baseStorage.close();
            closed = true;
            if (storagePath !== void 0) {
              const oldPath = join(storagePath, DEFAULT_SERVER_ID);
              const newPath = join(storagePath, candidateId);
              try {
                await rename(oldPath, newPath);
                logger.info(`Renamed storage "${DEFAULT_SERVER_ID}" to "${candidateId}"`);
                return candidateId;
              } catch (renameErr) {
                logger.warn(
                  `Failed to rename storage from "${DEFAULT_SERVER_ID}" to "${candidateId}"`,
                  renameErr
                );
                return DEFAULT_SERVER_ID;
              }
            }
            return DEFAULT_SERVER_ID;
          }
        } else {
          logger.error(`Multiple fabrics found, using new storage`, fabrics);
        }
      } finally {
        if (!closed) {
          await baseStorage.close();
        }
      }
      logger.info(`Existing "server" storage does not match fabric config, using new ID: ${candidateId}`);
    } catch (err) {
      logger.debug(`Could not verify "server" storage: ${err}`);
    }
  }
  logger.info(`Using new server ID format: ${candidateId}`);
  return candidateId;
}
export {
  DEFAULT_SERVER_ID,
  computeServerId,
  resolveServerId,
  storageExists
};
//# sourceMappingURL=ServerIdResolver.js.map
