import {
  mapCatalogToAstro
} from "./chunk-IR4IAKWS.js";

// src/watcher.js
import watcher from "@parcel/watcher";
import fs from "fs";
import { rimrafSync } from "rimraf";
async function watch(projectDirectory, catalogDirectory, callback = void 0) {
  const subscription = await watcher.subscribe(
    projectDirectory,
    compose(
      /**
       * @param {Error|null} err
       * @param {Event[]} events
       * @returns {unknown}
       */
      (err, events) => {
        if (err) {
          return;
        }
        for (let event of events) {
          const { path: filePath, type } = event;
          if (filePath.endsWith(".lock")) {
            continue;
          }
          if ((filePath.endsWith(".mdx") || filePath.endsWith(".md")) && !filePath.includes("snippets")) {
            continue;
          }
          const astroPaths = mapCatalogToAstro({
            filePath,
            astroDir: catalogDirectory,
            projectDir: projectDirectory
          });
          for (const astroPath of astroPaths) {
            switch (type) {
              case "create":
              case "update": {
                let stat;
                try {
                  stat = fs.statSync(filePath);
                } catch (err2) {
                  if (err2.code === "ENOENT") break;
                  throw err2;
                }
                if (stat.isDirectory()) {
                  fs.mkdirSync(astroPath, { recursive: true });
                } else {
                  retryEPERM(fs.cpSync)(filePath, astroPath);
                }
                break;
              }
              case "delete":
                retryEPERM(rimrafSync)(astroPath);
                break;
            }
          }
        }
      },
      callback
    ),
    {
      ignore: [`**/${catalogDirectory}/!(${projectDirectory})**`]
    }
  );
  return () => subscription.unsubscribe();
}
function compose(...fns) {
  return function(err, events) {
    fns.filter(Boolean).forEach((fn, i) => {
      try {
        fn(err, events);
      } catch (error) {
        console.error({ error });
        throw error;
      }
    });
  };
}
var MAX_RETRIES = 5;
var DELAY_MS = 100;
function retryEPERM(fn) {
  return (...args) => {
    let retries = 0;
    while (retries < MAX_RETRIES) {
      try {
        return fn(...args);
      } catch (err) {
        if (err.code !== "EPERM") throw err;
        setTimeout(() => {
        }, DELAY_MS);
        retries += 1;
      }
    }
  };
}

export {
  watch
};
