/**
 * @license
 * Copyright 2022-2026 Matter.js Authors
 * SPDX-License-Identifier: Apache-2.0
 */
import { Package } from "@nacho-iot/js-tools";
import { readFile } from "node:fs/promises";
import { isAbsolute } from "node:path";
import { State } from "../state.js";
import { PicsFile } from "./file.js";
const dataCache = /* @__PURE__ */ new WeakMap();
const filenameCache = /* @__PURE__ */ new WeakMap();
let nextFileNo = 1;
var PicsSource;
((PicsSource2) => {
  async function load(source) {
    let file = dataCache.get(source);
    if (file) {
      return file;
    }
    switch (source.kind) {
      case "composite":
        for (const subsource of source.sources) {
          const sourceFile = await load(subsource);
          if (file) {
            file.patch(sourceFile);
          } else {
            file = sourceFile;
          }
        }
        if (!file) {
          file = new PicsFile();
        }
        break;
      case "chip":
        file = new PicsFile(await State.container.read(source.name));
        break;
      case "file":
        file = new PicsFile(await readFile(resolve(source.name), "utf-8"));
        break;
      case "lines":
        file = new PicsFile(source.lines.split("\n").map((l) => l.trim()));
        break;
      case "values":
        file = new PicsFile(Object.entries(source.values).map(([key, value]) => `${key}=${value}`));
        break;
      default:
        throw new Error(`Invalid PICS source kind "${source.kind}"`);
    }
    dataCache.set(source, file);
    return file;
  }
  PicsSource2.load = load;
  async function save(target, file) {
    switch (target.kind) {
      case "chip":
        await State.container.write(target.name, file.toString());
        break;
      case "file":
        await State.container.write(resolve(target.name), file.toString());
        break;
      default:
        throw new Error(`Invalid PICS target kind "${target.kind}"`);
    }
  }
  PicsSource2.save = save;
  async function install(file) {
    let filename = filenameCache.get(file);
    if (filename) {
      return filename;
    }
    filename = `/pics-${nextFileNo++}.properties`;
    try {
      filenameCache.set(file, filename);
      await save({ kind: "chip", name: filename }, file);
    } catch (e) {
      filenameCache.delete(file);
      throw e;
    }
    return filename;
  }
  PicsSource2.install = install;
})(PicsSource || (PicsSource = {}));
function resolve(path) {
  if (isAbsolute(path)) {
    return path;
  }
  const testing = Package.findPackage("@matter/testing");
  if (testing.hasFile(path)) {
    return testing.resolve(path);
  }
  return resolve(path);
}
export {
  PicsSource
};
//# sourceMappingURL=source.js.map
