'use strict';

var chunkUF6I25ED_cjs = require('./chunk-UF6I25ED.cjs');
require('./chunk-K65UI6KX.cjs');
var chunkKHF2VXWO_cjs = require('./chunk-KHF2VXWO.cjs');
var fs = require('fs/promises');
var path = require('path');
var yauzl = require('yauzl');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

function _interopNamespace(e) {
  if (e && e.__esModule) return e;
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var fs__default = /*#__PURE__*/_interopDefault(fs);
var path__default = /*#__PURE__*/_interopDefault(path);
var yauzl__namespace = /*#__PURE__*/_interopNamespace(yauzl);

function parseJson(content, fileName) {
  try {
    return JSON.parse(content);
  } catch (error) {
    throw new Error(
      `Failed to parse JSON in file '${fileName}': ${error instanceof Error ? error.message : String(error)}`
    );
  }
}
chunkKHF2VXWO_cjs.__name(parseJson, "parseJson");
function removeJsonExtension(fileName) {
  return fileName.replace(/\.json$/i, "");
}
chunkKHF2VXWO_cjs.__name(removeJsonExtension, "removeJsonExtension");
async function loadZipToMemory(zipPath) {
  return new Promise((resolve, reject) => {
    const filesContent = {};
    yauzl__namespace.open(zipPath, { lazyEntries: true }, (err, zipfile) => {
      if (err) {
        reject(new Error(`Failed to open ZIP file: ${err.message}`));
        return;
      }
      if (!zipfile) {
        reject(new Error("Failed to open ZIP file"));
        return;
      }
      zipfile.readEntry();
      zipfile.on("entry", (entry) => {
        if (entry.fileName.endsWith("/")) {
          zipfile.readEntry();
          return;
        }
        if (entry.fileName.endsWith(".json")) {
          zipfile.openReadStream(entry, (err2, readStream) => {
            if (err2) {
              reject(new Error(`Failed to read entry ${entry.fileName}: ${err2.message}`));
              return;
            }
            if (!readStream) {
              reject(new Error(`Failed to read entry ${entry.fileName}`));
              return;
            }
            let data = "";
            readStream.on("data", (chunk) => {
              data += chunk;
            });
            readStream.on("end", () => {
              try {
                const fileNameWithoutExt = removeJsonExtension(entry.fileName);
                filesContent[fileNameWithoutExt] = parseJson(data, entry.fileName);
                zipfile.readEntry();
              } catch (error) {
                reject(error);
              }
            });
            readStream.on("error", (streamErr) => {
              reject(new Error(`Error reading stream for ${entry.fileName}: ${streamErr.message}`));
            });
          });
        } else {
          zipfile.readEntry();
        }
      });
      zipfile.on("end", () => {
        resolve(filesContent);
      });
      zipfile.on("error", (zipErr) => {
        reject(new Error(`ZIP file error: ${zipErr.message}`));
      });
    });
  });
}
chunkKHF2VXWO_cjs.__name(loadZipToMemory, "loadZipToMemory");
function detectFileType(filePath, stats) {
  if (stats.isDirectory()) {
    return "DIRECTORY" /* DIRECTORY */;
  }
  const ext = path__default.default.extname(filePath).toLowerCase();
  if (ext === ".zip") return "ZIP" /* ZIP */;
  if (ext === ".json") return "JSON" /* JSON */;
  throw new Error(`Unsupported file type: ${ext}`);
}
chunkKHF2VXWO_cjs.__name(detectFileType, "detectFileType");
async function collectJsonFiles(filePath) {
  const fileStats = await fs__default.default.stat(filePath);
  const fileType = detectFileType(filePath, fileStats);
  switch (fileType) {
    case "ZIP" /* ZIP */: {
      const filesContent = await loadZipToMemory(filePath);
      return filesContent;
    }
    case "JSON" /* JSON */: {
      const content = await fs__default.default.readFile(filePath, "utf-8");
      const fileName = path__default.default.basename(filePath);
      const fileNameWithoutExt = removeJsonExtension(fileName);
      const parsed = parseJson(content, fileName);
      return { [fileNameWithoutExt]: parsed };
    }
    case "DIRECTORY" /* DIRECTORY */: {
      const files = await fs__default.default.readdir(filePath);
      const jsonFiles = {};
      for (const file of files) {
        if (path__default.default.extname(file).toLowerCase() === ".json") {
          const fullPath = path__default.default.join(filePath, file);
          const content = await fs__default.default.readFile(fullPath, "utf-8");
          const parsed = parseJson(content, file);
          const fileNameWithoutExt = removeJsonExtension(file);
          jsonFiles[fileNameWithoutExt] = parsed;
        }
      }
      return jsonFiles;
    }
  }
}
chunkKHF2VXWO_cjs.__name(collectJsonFiles, "collectJsonFiles");

// src/processor/utils/normalizer.ts
function normalizeJsonFiles(jsonFiles) {
  const isSingleEntry = Object.keys(jsonFiles).length === 1;
  if (!isSingleEntry) {
    return jsonFiles;
  }
  const [, content] = Object.entries(jsonFiles)[0];
  if (typeof content !== "object" || content === null) {
    throw new Error("File content is not an object");
  }
  const hasMetadata = Object.keys(content).some(
    (key) => key.startsWith("$")
  );
  if (hasMetadata) {
    return content;
  }
  return jsonFiles;
}
chunkKHF2VXWO_cjs.__name(normalizeJsonFiles, "normalizeJsonFiles");

// src/processor/processFiles.ts
async function processTokensFromFiles({
  path: inputPath,
  schemas,
  activeSets,
  activeTheme,
  builder
}) {
  await chunkUF6I25ED_cjs.fetchAndRegisterSchemas(schemas ?? []);
  const jsonFiles = await collectJsonFiles(inputPath);
  const normalizedFiles = normalizeJsonFiles(jsonFiles);
  return chunkUF6I25ED_cjs.processTokenSets(normalizedFiles, {
    activeSets,
    activeTheme,
    builder
  });
}
chunkKHF2VXWO_cjs.__name(processTokensFromFiles, "processTokensFromFiles");

exports.processTokensFromFiles = processTokensFromFiles;
//# sourceMappingURL=processor-node.cjs.map
//# sourceMappingURL=processor-node.cjs.map