import * as fsPromises from "fs/promises";
import copy from "rollup-plugin-copy";
import scss from "rollup-plugin-scss";
import {defineConfig, Plugin} from "vite";

const moduleVersion = process.env.MODULE_VERSION;
const githubProject = process.env.GH_PROJECT;
const githubTag = process.env.GH_TAG;

export default defineConfig({
    build: {
        sourcemap: true,
        rollupOptions: {
            input: "src/ts/dice-tower.ts",
            output: {
                entryFileNames: "scripts/[name].js",
                dir: "dist",
                format: "es",
                assetFileNames: "[name][extname]"
            },
        },
    },
    plugins: [
        scss({
            name: "styles/style.css",
            sourceMap: true,
            watch: ["src/styles/*.scss"],
        }),
        copy({
            targets: [
                { src: "src/languages", dest: "dist" },
                { src: "src/templates", dest: "dist" },
                { src: "src/libs", dest: "dist" },
                { src: "src/textures", dest: "dist" },
            ],
            hook: "writeBundle",
        }),
        updateModuleManifestPlugin(),
    ],
});

function updateModuleManifestPlugin(): Plugin {
    return {
        name: "update-module-manifest",
        async writeBundle(): Promise<void> {
            const packageContents = JSON.parse(
                await fsPromises.readFile("./package.json", "utf-8")
            ) as Record<string, unknown>;
            const version = moduleVersion || (packageContents.version as string);
            const description = (packageContents.description as string);
            const manifestContents: string = await fsPromises.readFile(
                "src/module.json",
                "utf-8"
            );
            const manifestJson = JSON.parse(manifestContents) as Record<
                string,
                unknown
            >;
            manifestJson["version"] = version;
            manifestJson["description"] = description;
            if (githubProject) {
                const baseUrl = `https://github.com/${githubProject}/releases`;
                manifestJson["manifest"] = `${baseUrl}/latest/download/module.json`;
                if (githubTag) {
                    manifestJson[
                        "download"
                        ] = `${baseUrl}/download/${githubTag}/module.zip`;
                }
            }
            await fsPromises.writeFile(
                "dist/module.json",
                JSON.stringify(manifestJson, null, 4)
            );
        },
    };
}
