import babel from "@rollup/plugin-babel";
import nodeResolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import terser from "@rollup/plugin-terser";
import Path from "path";
import fs from "fs";

const changeVersion = () => {
    const version = fs.readFileSync(".version", { encoding: "utf8" }) || "1.0.0";
    let versionNumber = parseInt(version.replace(/\./g, ''));
    versionNumber += 1;
    const newVersion = versionNumber.toString().split('').join('.');
    fs.writeFileSync(".version", newVersion);
    return newVersion;
}
const changeManifest = (others = {}) => {
    let manifest = JSON.parse(fs.readFileSync("manifest.json", { encoding: "utf8" }));
    manifest = { ...manifest, version: changeVersion(), ...others }
    fs.writeFileSync("dist/manifest.json", JSON.stringify(manifest));
}
const pack = (input, options = {}) => {
    const fn = Path.parse(input);
    const { isProd = false, outDir = "dist/js/" } = options;
    fs.mkdirSync(outDir, { recursive: true });
    const plugins = [
        nodeResolve({
            browser: true,
        }),
        commonjs({
            include: /node_modules/,
            requireReturnsDefault: "auto",
        }),
    ]
    const output = {
        file: Path.join(outDir, fn.base),
        format: "iife",
        name: "G",
    }
    if (isProd) {
        output.file = Path.join(outDir, `${fn.name}.min.js`);
        output.sourcemap = true;
        plugins.push(
            babel({
                babelHelpers: "bundled",
            }),
            terser()
        );
    }
    return {
        input,
        output,
        plugins
    }
}
const conf = [];
const nodeEnv = process.env.NODE_ENV?.trim() || 'DEV';
console.log(`NODE_ENV: ${nodeEnv}`);
if (nodeEnv == 'TEST') {
    conf.push(pack("test/main.js", { outDir: "test/js" }))
} else {
    changeManifest();
    const inputs = ["src/main.js", "src/popup.js", "src/background.js"];
    inputs.forEach(input => conf.push(pack(input, { isProd: nodeEnv == 'PROD' })));
}
export default conf;
