import { compilePack, extractPack } from "@foundryvtt/foundryvtt-cli";
import { promises as fs } from "node:fs";
import path from "node:path";

const ROOT_DIR = process.cwd();

export class CompendiumsManager {
  static async packToDistDir(srcDir = "packs_src", distDir = "packs", mode = "json") {
    const yaml = mode === "yaml";
    const packs = await fs.readdir(path.join(ROOT_DIR, srcDir));
    for (const pack of packs) {
      if (pack.startsWith(".")) continue;

      const sourcePath = path.join(ROOT_DIR, srcDir, pack);
      const targetPath = path.join(ROOT_DIR, distDir, pack);
      await fs.rm(targetPath, { recursive: true, force: true });
      console.log(`Packing ${pack}`);
      await compilePack(sourcePath, targetPath, { yaml });
    }
  }

  static async unpackToSrcDir(srcDir = "packs_src", distDir = "packs", mode = "json") {
    const yaml = mode === "yaml";
    const packs = await fs.readdir(path.join(ROOT_DIR, distDir));
    for (const pack of packs) {
      if (pack.startsWith(".")) continue;

      const sourcePath = path.join(ROOT_DIR, distDir, pack);
      const targetPath = path.join(ROOT_DIR, srcDir, pack);
      await fs.mkdir(targetPath, { recursive: true });

      const existingFiles = await fs.readdir(targetPath);
      for (const file of existingFiles) {
        await fs.unlink(path.join(targetPath, file));
      }

      console.log(`Unpacking ${pack}`);
      await extractPack(sourcePath, targetPath, {
        yaml,
        transformName: (doc) => CompendiumsManager.transformName(doc, yaml)
      });
    }
  }

  static transformName(doc, yaml) {
    const safeName = (doc.name ?? doc._id ?? "document").replace(/[^a-zA-Z0-9_-]+/g, "_");
    const type = doc._key?.split("!")[1] ?? doc.type ?? "document";
    const extension = yaml ? "yml" : "json";
    return `${type}_${safeName}_${doc._id}.${extension}`;
  }
}
