const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const glob = require('glob');
const path = require('path');
const fs = require('fs'); // ✅ Added fs to check file existence
const CopyPlugin = require('copy-webpack-plugin');
const WatchExternalFilesPlugin = require('webpack-watch-files-plugin').default;

/**
 * Get Entry Points
 * Structure: src/blocks/[template]/[block] -> build/blocks/[template]/[block]
 */
const getBlockEntryPoints = () => {
    // 1. Find all block.json files inside sub-folders of src/blocks
    const blockJsonFiles = glob.sync('./src/blocks/*/*/block.json');

    return blockJsonFiles.reduce((acc, filepath) => {
        const blockDir = path.dirname(filepath);

        // 2. Calculate path relative to 'src' (Includes 'blocks' in the name)
        // Example: src/blocks/author-pro/hero -> blocks/author-pro/hero
        const entryName = path.relative('./src', blockDir);

        // ✅ 3. Add index.js (Editor Script)
        const indexFile = path.resolve(blockDir, 'index.js');
        if (fs.existsSync(indexFile)) {
            acc[entryName + '/index'] = indexFile;
        }

        // ✅ 4. Add view.js (Frontend Script) - NEW ADDITION
        // This checks if view.js exists in the block folder and adds it to build
        const viewFile = path.resolve(blockDir, 'view.js');
        if (fs.existsSync(viewFile)) {
            acc[entryName + '/view'] = viewFile;
        }

        return acc;
    }, {});
};

module.exports = {
    ...defaultConfig,
    entry: {
        ...defaultConfig.entry,
        ...getBlockEntryPoints(),
        // Main style/script entry
        'index': './src/index.js',
        'template-library/index': './src/template-library/index.js',
    },
    output: {
        ...defaultConfig.output,
        path: path.resolve(__dirname, 'build'),
        filename: '[name].js', // Will output index.js and view.js in correct folders
        clean: true,
    },
    // Performance hints to ignore large file warnings
    performance: {
        hints: false,
        maxEntrypointSize: 512000,
        maxAssetSize: 512000
    },
    plugins: [
        ...defaultConfig.plugins,
        new CopyPlugin({
            patterns: [
                {
                    // Copy assets maintaining the 'blocks' structure
                    from: '**/{block.json,render.php,*.jpg,*.png,*.svg}',
                    context: 'src',
                    to: '[path][name][ext]',
                    noErrorOnMissing: true,
                    globOptions: {
                        ignore: ['**/node_modules/**'],
                    },
                },
            ],
        }),
        new WatchExternalFilesPlugin({
            files: [
                './src/blocks/**/*.php',
                './src/blocks/**/*.js',
            ]
        }),
    ],
};