import { fetchAndRegisterSchemas, processTokenSets } from './chunk-IQQQZZRV.js';
import './chunk-4F6AO25C.js';
import { __name } from './chunk-SLVAZICD.js';
import fs from 'fs/promises';
import path from 'path';
import * as yauzl from '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)}`
    );
  }
}
__name(parseJson, "parseJson");
function removeJsonExtension(fileName) {
  return fileName.replace(/\.json$/i, "");
}
__name(removeJsonExtension, "removeJsonExtension");
async function loadZipToMemory(zipPath) {
  return new Promise((resolve, reject) => {
    const filesContent = {};
    yauzl.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}`));
      });
    });
  });
}
__name(loadZipToMemory, "loadZipToMemory");
function detectFileType(filePath, stats) {
  if (stats.isDirectory()) {
    return "DIRECTORY" /* DIRECTORY */;
  }
  const ext = path.extname(filePath).toLowerCase();
  if (ext === ".zip") return "ZIP" /* ZIP */;
  if (ext === ".json") return "JSON" /* JSON */;
  throw new Error(`Unsupported file type: ${ext}`);
}
__name(detectFileType, "detectFileType");
async function collectJsonFiles(filePath) {
  const fileStats = await fs.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.readFile(filePath, "utf-8");
      const fileName = path.basename(filePath);
      const fileNameWithoutExt = removeJsonExtension(fileName);
      const parsed = parseJson(content, fileName);
      return { [fileNameWithoutExt]: parsed };
    }
    case "DIRECTORY" /* DIRECTORY */: {
      const files = await fs.readdir(filePath);
      const jsonFiles = {};
      for (const file of files) {
        if (path.extname(file).toLowerCase() === ".json") {
          const fullPath = path.join(filePath, file);
          const content = await fs.readFile(fullPath, "utf-8");
          const parsed = parseJson(content, file);
          const fileNameWithoutExt = removeJsonExtension(file);
          jsonFiles[fileNameWithoutExt] = parsed;
        }
      }
      return jsonFiles;
    }
  }
}
__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;
}
__name(normalizeJsonFiles, "normalizeJsonFiles");

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

export { processTokensFromFiles };
//# sourceMappingURL=processor-node.js.map
//# sourceMappingURL=processor-node.js.map