// extract-map.js
const fs = require("fs-extra");
const path = require("path");

(async () => {
  const mapPath = path.resolve(__dirname, "./raw_server_files/main.886bb15c.chunk.css.map");
  const outputDir = path.resolve(__dirname, "sources_from_map");

  const rawMap = await fs.readFile(mapPath, "utf-8");
  const map = JSON.parse(rawMap);

  if (!map.sources || !map.sourcesContent) {
    throw new Error("❌ Invalid .map file: missing sources or sourcesContent");
  }

  let saved = 0;

  for (let i = 0; i < map.sources.length; i++) {
    const src = map.sources[i];
    const content = map.sourcesContent[i];
    if (!src || !content) continue;

    // Clean up the filename
    let filePath = src
      .replace(/^webpack:\/\//, "")
      .replace(/^\/+/, "")
      .replace(/\?.*$/, ""); // remove query params

    if (filePath.endsWith("/")) filePath += "index.js";
    if (!path.extname(filePath)) filePath += ".js";

    const outputPath = path.resolve(outputDir, filePath);
    await fs.ensureDir(path.dirname(outputPath));
    await fs.writeFile(outputPath, content, "utf-8");

    console.log(`💾 Saved: ${filePath}`);
    saved++;
  }

  if (saved === 0) {
    console.warn("⚠️ No files were saved.");
  } else {
    console.log(`✅ Extracted and saved ${saved} files to: ${outputDir}`);
  }
})();
