import { readdir } from "node:fs/promises";
import * as path from "node:path";
import chalk from "chalk";

import { commandHandler, helpers } from "../core";
import { ASSETS_FOLDER, PROFILES_FOLDER } from "../consts";

import type { ProfileFile } from "./types";
import type { Command } from "../core";

const syncUpCommand: Command = {
  name: "sync-up",
  description: "Syncs up all assets folders with the manifest. Usage: sync-up",
  execute: async () => {
    if (await helpers.manifest.isFolderExists()) {
      const dirEntries = await readdir(PROFILES_FOLDER, {
        withFileTypes: true,
      });

      for (const entry of dirEntries) {
        const file = Bun.file(path.join(PROFILES_FOLDER, entry.name));
        const data: ProfileFile = JSON.parse(await file.text());

        console.log(chalk.green(`Syncing up profile: ${data.id}`));

        const pathToAssets = path.join(ASSETS_FOLDER, data.assetsFolder);
        const generatedManifest = await helpers.manifest.generate(pathToAssets);

        await helpers.manifest.save(
          data.id,
          JSON.stringify(generatedManifest),
          await helpers.manifest.isExists(data.id),
        );
      }

      console.log(chalk.green("Sync up complete!"));
    }
  },
};

commandHandler.registerCommand(syncUpCommand);
