import commonjs from "@rollup/plugin-commonjs";
import resolve from "@rollup/plugin-node-resolve";
// import replace from "@rollup/plugin-replace";
// import dotenv from "dotenv";
// import fs from "fs";
import injectProcessEnv from "rollup-plugin-inject-process-env";

// import { visualizer } from "rollup-plugin-visualizer";

// import scss from 'rollup-plugin-scss';
// import sass from "sass";
import postcss from "rollup-plugin-postcss";
import postcssModules from "postcss-modules";

import { terser } from "rollup-plugin-terser";
import typescript from "rollup-plugin-typescript2";

import external from "rollup-plugin-peer-deps-external";
import pkg from "./package.json";

import filesize from "rollup-plugin-filesize";
import replace from "rollup-plugin-replace";
import { execSync } from "child_process";

process.env.NODE_ENV = "production";

const cssExportMap = {};

// Function to get the current Git branch
const getCurrentBranch = () => {
    try {
        return execSync("git rev-parse --abbrev-ref HEAD").toString().trim();
    } catch (e) {
        // console.error(e);
        return "Unknown";
    }
};

// var envs = fs
// .readdirSync(".")
// .filter((fn) => fn.endsWith(".env"))
// .map((f) => f.substring(0, f.length - 4));

const buildScss = (extract) =>
    postcss({
        include: ["/**/*.css", "/**/*.scss"],
        plugins: [
            postcssModules({
                getJSON(id, exportTokens) {
                    cssExportMap[id] = exportTokens;
                },
                // generateScopedName: "[name]_X_[local]__Y__[hash:base64:5]"
                // generateScopedName: "[local]"
                generateScopedName(name) {
                    // Exclude material ui
                    const match = name.match(/_Mui(.*?)__/);
                    if (match) {
                        const muiClass = `Mui${match[1]}`;
                        console.log(`Excluding MUI class: ".${muiClass}"`);
                        return muiClass;
                    }

                    return name;
                },
            }),
        ],
        getExportNamed: false,
        getExport(id) {
            return cssExportMap[id];
        },
        extract,
        autoModules: true,
    });

const plugins = () => [
    replace({
        "process.env.MODULE_MODE": JSON.stringify("true"),
        __BUILD_DATE__: () => new Date().toLocaleString(),
        __GIT_BRANCH__: getCurrentBranch(),
    }),
    buildScss(false),
    commonjs(),
    external(),
    resolve({ preferBuiltins: true, mainFields: ["browser"] }),
    typescript(),
    //   terser(),
    filesize(),
];

// const pluginsStandalone = (args) => [
//     buildScss(true),

//     replace({
//         "process.env.NODE_ENV": () => JSON.stringify(process.env.NODE_ENV),
//         preventAssignment: true,
//     }),

//     commonjs(),
//     injectProcessEnv(args),
//     resolve({ preferBuiltins: true, mainFields: ["browser"] }),
//     typescript(),
//     terser(),
//     filesize(),

//     visualizer()
// ];

const pluginUmd = (args) => [
    replace({
        __BUILD_DATE__: () => new Date().toLocaleString(),
        __GIT_BRANCH__: getCurrentBranch(),
    }),

    buildScss(true),

    resolve(),
    commonjs(),
    injectProcessEnv(args),
    resolve({ preferBuiltins: true, mainFields: ["browser"] }),
    typescript(),
    terser(),
    filesize(),

    // visualizer(),
];

function cjs(fileName) {
    return {
        file: fileName,
        format: "cjs",
        exports: "named",
        sourcemap: false,
    };
}

function es(fileName) {
    return {
        file: fileName,
        format: "es",
        exports: "named",
        sourcemap: true,
        globals: {
            react: "React",
            "react-dom": "ReactDOM",
        },
    };
}

function umd(fileName) {
    return {
        file: fileName,
        format: "umd",
        exports: "named",
        name: "XappContactApp",
        sourcemap: false,
        globals: {
            // react: "React",
            // "react-dom": "ReactDOM"
        },
    };
}

// function iife(fileName) {
//     return {
//         file: fileName,
//         format: "iife",
//         exports: "named",
//         sourcemap: false,
//         name: "XAPPFormWidget"
//     };
// }

// const envConfigs = envs.map((envName) => ({
//     name: envName,
//     config: dotenv.config({
//         path: `${envName}.env`,
//     }).parsed,
// }));

const config = [
    {
        input: "src/index.tsx",
        output: [cjs(pkg.main), es(pkg.module)],
        plugins: plugins(),
    },
    {
        input: "src/App.tsx",
        output: [umd("dist/xapp-contact-page.js")],
        plugins: pluginUmd(true),
        // external: ["react", "react-dom"],
    },
    // {
    //     input: "src/App.tsx",
    //     output: [iife(`dist/xapp-form-widget.js`)],
    //     plugins: pluginsStandalone({})
    // },
    // ...envConfigs.map((envConfig) => ({
    //     input: "src/App.tsx",
    //     output: [iife(`build/${envConfig.name}/xapp-form-widget.js`)],
    //     plugins: pluginsStandalone(envConfig.config),
    // })),
];

export default config;
