<?php
defined( 'ABSPATH' ) || exit;

class SITECL_Plugin_Bloat {

    /**
     * Scan each active plugin's directory and sum its JS + CSS asset sizes.
     * This works in any context (admin, REST, cron) without needing front-end hooks.
     */
    public static function scan(): array {
        $active = (array) get_option( 'active_plugins', [] );

        if ( empty( $active ) ) {
            return [];
        }

        $plugin_sizes = [];

        foreach ( $active as $plugin_file ) {
            $slug       = explode( '/', $plugin_file )[0];
            $plugin_dir = WP_PLUGIN_DIR . '/' . $slug;

            if ( ! is_dir( $plugin_dir ) ) {
                continue;
            }

            $kb = self::measure_assets( $plugin_dir );
            if ( $kb > 0 ) {
                $plugin_sizes[ $slug ] = $kb;
            }
        }

        arsort( $plugin_sizes );

        $issues = [];

        foreach ( $plugin_sizes as $slug => $kb ) {
            if ( $kb < 100 ) {
                continue;
            }

            $issues[] = [
                'type'        => 'plugin_bloat',
                'severity'    => $kb >= 500 ? 'warning' : 'info',
                'title'       => sprintf(
                    /* translators: %1$s: plugin slug, %2$s: total asset size in KB */
                    __( '%1$s ships %2$s KB of JS/CSS assets', 'site-cliniq' ),
                    esc_html( $slug ),
                    number_format( $kb, 1 )
                ),
                'detail'      => sprintf(
                    /* translators: %s: total asset size in KB */
                    __( 'This plugin\'s JS and CSS files total %s KB. Large front-end assets slow page load for every visitor.', 'site-cliniq' ),
                    number_format( $kb, 1 )
                ),
                'plugin_slug' => $slug,
                'kb'          => $kb,
            ];
        }

        return $issues;
    }

    // -------------------------------------------------------------------------

    /**
     * Recursively sum all .js and .css file sizes under a plugin directory.
     * Skips source maps (.map), node_modules, and vendor directories.
     */
    private static function measure_assets( string $plugin_dir ): float {
        $total = 0.0;

        try {
            $iter = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator( $plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS ),
                RecursiveIteratorIterator::LEAVES_ONLY
            );

            foreach ( $iter as $file ) {
                if ( ! $file->isFile() ) {
                    continue;
                }

                // Skip heavy vendor/node directories.
                $path = $file->getPathname();
                if ( str_contains( $path, '/node_modules/' ) || str_contains( $path, '/vendor/' ) ) {
                    continue;
                }

                $ext = strtolower( $file->getExtension() );
                if ( 'js' !== $ext && 'css' !== $ext ) {
                    continue;
                }

                // Skip source maps.
                if ( str_ends_with( $file->getFilename(), '.map' ) ) {
                    continue;
                }

                $total += $file->getSize();
            }
        } catch ( Exception $e ) {
            return 0.0;
        }

        return round( $total / 1024, 1 );
    }
}
