<?php

/**
 * Competitor Detector Service
 *
 * Detects active SEO and performance plugins that may conflict with ProRank SEO
 *
 * @package ProRank\SEO\Core\Compatibility
 * @since   0.1.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Core\Compatibility;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}


/**
 * CompetitorDetector class
 *
 * Service to detect other active SEO plugins
 */


class CompetitorDetector {
    
    /**
     * Map of known competitor plugins
     *
     * @var array<string, string>
     */
    private static array $competitor_plugins = [
        // Yoast SEO + add-ons
        'wordpress-seo/wp-seo.php' => 'Yoast SEO',
        'wordpress-seo-premium/wp-seo-premium.php' => 'Yoast SEO Premium',
        'wpseo-local/wpseo-local.php' => 'Yoast Local SEO',
        'wpseo-video/wpseo-video.php' => 'Yoast Video SEO',
        'wpseo-news/wpseo-news.php' => 'Yoast News SEO',
        'woocommerce-seo/woocommerce-seo.php' => 'Yoast WooCommerce SEO',
        'wpseo-woocommerce/wpseo-woocommerce.php' => 'Yoast WooCommerce SEO',
        
        // Rank Math
        'seo-by-rank-math/rank-math.php' => 'Rank Math SEO',
        'seo-by-rank-math-pro/rank-math-pro.php' => 'Rank Math SEO Pro',

        // WP Schema Pro
        'wp-schema-pro/wp-schema-pro.php' => 'WP Schema Pro',
        'schema-pro/schema-pro.php' => 'Schema Pro',

        // SureRank (bundled with Starter Templates/Astra)
        'surerank/surerank.php' => 'SureRank SEO',

        // SureTriggers / SureCart ecosystem
        'suretriggers/suretriggers.php' => 'SureTriggers',
        
        // All in One SEO
        'all-in-one-seo-pack/all_in_one_seo_pack.php' => 'All in One SEO',
        'all-in-one-seo-pack-pro/all_in_one_seo_pack.php' => 'All in One SEO Pro',
        
        // SEOPress
        'wp-seopress/seopress.php' => 'SEOPress',
        'wp-seopress-pro/seopress-pro.php' => 'SEOPress Pro',
        
        // The SEO Framework
        'autodescription/autodescription.php' => 'The SEO Framework',

        // SEOKEY
        'seokey/seokey.php' => 'SEOKEY',
        
        // Squirrly SEO
        'squirrly-seo/squirrly.php' => 'Squirrly SEO',
        
        // SmartCrawl
        'smartcrawl-seo/wpmu-dev-seo.php' => 'SmartCrawl SEO',
        
        // SEO Ultimate
        'seo-ultimate/seo-ultimate.php' => 'SEO Ultimate',
        
        // Platinum SEO
        'platinum-seo-pack/platinum-seo-pack.php' => 'Platinum SEO Pack',
        
        // Greg's High Performance SEO
        'gregs-high-performance-seo/ghpseo.php' => 'Greg\'s High Performance SEO',
        
        // WP Meta SEO
        'wp-meta-seo/wp-meta-seo.php' => 'WP Meta SEO',
        
        // Premium SEO Pack
        'premium-seo-pack/index.php' => 'Premium SEO Pack',
        
        // SEO Booster
        'seo-booster/seo-booster.php' => 'SEO Booster',
        
        // SEO Optimized Images
        'seo-optimized-images/seo-optimized-images.php' => 'SEO Optimized Images',
        
        // Slim SEO
        'slim-seo/slim-seo.php' => 'Slim SEO',
        'slim-seo-schema/slim-seo-schema.php' => 'Slim SEO Schema',
        'slim-seo-link-manager/slim-seo-link-manager.php' => 'Slim SEO Link Manager',
        'slim-seo-redirection/slim-seo-redirection.php' => 'Slim SEO Redirection',
        
        // SEO 2
        'seo-2/seo.php' => 'SEO 2',
        
        // Simply SEO
        'simply-seo/simply-seo.php' => 'Simply SEO',
        
        // SEO Plugin by Squirrly
        'seo-plugin-by-squirrly/squirrly.php' => 'SEO Plugin by Squirrly',

        // Performance / caching / optimization
        'wp-rocket/wp-rocket.php' => 'WP Rocket',
        'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
        'wp-super-cache/wp-cache.php' => 'WP Super Cache',
        'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
        'cache-enabler/cache-enabler.php' => 'Cache Enabler',
        'autoptimize/autoptimize.php' => 'Autoptimize',
        'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
        'sg-cachepress/sg-cachepress.php' => 'SiteGround Optimizer',
        'nitropack/nitropack.php' => 'NitroPack',
        'perfmatters/perfmatters.php' => 'Perfmatters',
        'flying-press/flying-press.php' => 'FlyingPress',
        'flying-scripts/flying-scripts.php' => 'Flying Scripts',
        'asset-cleanup/asset-cleanup.php' => 'Asset CleanUp',
        'asset-cleanup-pro/asset-cleanup.php' => 'Asset CleanUp Pro',
        'async-javascript/async-javascript.php' => 'Async JavaScript',
        'wp-optimize/wp-optimize.php' => 'WP-Optimize',
        'swift-performance-lite/performance.php' => 'Swift Performance Lite',
        'comet-cache/comet-cache.php' => 'Comet Cache',
        'breeze/breeze.php' => 'Breeze',
        'speedycache/speedycache.php' => 'SpeedyCache',
        
        // W3 Total Cache (has SEO features)
        'w3-total-cache/w3-total-cache.php' => 'W3 Total Cache (SEO Features)',
        
        // Jetpack (has SEO features)
        'jetpack/jetpack.php' => 'Jetpack (SEO Features)',

        // Image optimization
        'shortpixel-image-optimiser/wp-shortpixel.php' => 'ShortPixel Image Optimizer',
        'imagify/imagify.php' => 'Imagify',
        'wp-smushit/wp-smush.php' => 'Smush',
        'ewww-image-optimizer/ewww-image-optimizer.php' => 'EWWW Image Optimizer',
        'optimole-wp/optimole-wp.php' => 'Optimole',
        'tiny-compress-images/tiny-compress-images.php' => 'TinyPNG',
        'webp-express/webp-express.php' => 'WebP Express',
        'converter-for-media/converter-for-media.php' => 'Converter for Media',
        're-smush-it/resmushit.php' => 'reSmush.it Image Optimizer',
        'robin-image-optimizer/robin-image-optimizer.php' => 'Robin Image Optimizer',

        // Internal linking
        'link-whisper/link-whisper.php' => 'Link Whisper',
        'link-whisper-premium/link-whisper.php' => 'Link Whisper Premium',
    ];

    /**
     * Internal linking plugins that can conflict with ProRank's link suggestions.
     *
     * @var array<string, string>
     */
    private static array $internal_linking_competitor_plugins = [
        'link-whisper/link-whisper.php' => 'Link Whisper',
        'link-whisper-premium/link-whisper.php' => 'Link Whisper Premium',
        'slim-seo-link-manager/slim-seo-link-manager.php' => 'Slim SEO Link Manager',
    ];

    /**
     * SEO plugins that can duplicate metadata/schema/sitemaps with ProRank.
     *
     * @var array<string, string>
     */
    private static array $seo_competitor_plugins = [
        // Yoast SEO + add-ons
        'wordpress-seo/wp-seo.php' => 'Yoast SEO',
        'wordpress-seo-premium/wp-seo-premium.php' => 'Yoast SEO Premium',
        'wpseo-local/wpseo-local.php' => 'Yoast Local SEO',
        'wpseo-video/wpseo-video.php' => 'Yoast Video SEO',
        'wpseo-news/wpseo-news.php' => 'Yoast News SEO',
        'woocommerce-seo/woocommerce-seo.php' => 'Yoast WooCommerce SEO',
        'wpseo-woocommerce/wpseo-woocommerce.php' => 'Yoast WooCommerce SEO',

        // Rank Math
        'seo-by-rank-math/rank-math.php' => 'Rank Math SEO',
        'seo-by-rank-math-pro/rank-math-pro.php' => 'Rank Math SEO Pro',

        // WP Schema Pro
        'wp-schema-pro/wp-schema-pro.php' => 'WP Schema Pro',
        'schema-pro/schema-pro.php' => 'Schema Pro',

        // Other SEO suites
        'surerank/surerank.php' => 'SureRank SEO',
        'all-in-one-seo-pack/all_in_one_seo_pack.php' => 'All in One SEO',
        'all-in-one-seo-pack-pro/all_in_one_seo_pack.php' => 'All in One SEO Pro',
        'wp-seopress/seopress.php' => 'SEOPress',
        'wp-seopress-pro/seopress-pro.php' => 'SEOPress Pro',
        'autodescription/autodescription.php' => 'The SEO Framework',
        'seokey/seokey.php' => 'SEOKEY',
        'squirrly-seo/squirrly.php' => 'Squirrly SEO',
        'smartcrawl-seo/wpmu-dev-seo.php' => 'SmartCrawl SEO',
        'seo-ultimate/seo-ultimate.php' => 'SEO Ultimate',
        'platinum-seo-pack/platinum-seo-pack.php' => 'Platinum SEO Pack',
        'gregs-high-performance-seo/ghpseo.php' => 'Greg\'s High Performance SEO',
        'wp-meta-seo/wp-meta-seo.php' => 'WP Meta SEO',
        'premium-seo-pack/index.php' => 'Premium SEO Pack',
        'seo-booster/seo-booster.php' => 'SEO Booster',
        'seo-optimized-images/seo-optimized-images.php' => 'SEO Optimized Images',
        'slim-seo/slim-seo.php' => 'Slim SEO',
        'slim-seo-schema/slim-seo-schema.php' => 'Slim SEO Schema',
        'slim-seo-link-manager/slim-seo-link-manager.php' => 'Slim SEO Link Manager',
        'slim-seo-redirection/slim-seo-redirection.php' => 'Slim SEO Redirection',
        'seo-2/seo.php' => 'SEO 2',
        'simply-seo/simply-seo.php' => 'Simply SEO',
        'seo-plugin-by-squirrly/squirrly.php' => 'SEO Plugin by Squirrly',
    ];

    /**
     * Performance-focused competitors that can duplicate caching, minification,
     * asset optimization, lazy-loading, and image optimization behavior.
     *
     * @var array<string, string>
     */
    private static array $performance_competitor_plugins = [
        // Performance / caching / optimization
        'wp-rocket/wp-rocket.php' => 'WP Rocket',
        'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
        'wp-super-cache/wp-cache.php' => 'WP Super Cache',
        'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
        'cache-enabler/cache-enabler.php' => 'Cache Enabler',
        'autoptimize/autoptimize.php' => 'Autoptimize',
        'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
        'sg-cachepress/sg-cachepress.php' => 'SiteGround Optimizer',
        'nitropack/nitropack.php' => 'NitroPack',
        'perfmatters/perfmatters.php' => 'Perfmatters',
        'flying-press/flying-press.php' => 'FlyingPress',
        'flying-scripts/flying-scripts.php' => 'Flying Scripts',
        'asset-cleanup/asset-cleanup.php' => 'Asset CleanUp',
        'asset-cleanup-pro/asset-cleanup.php' => 'Asset CleanUp Pro',
        'async-javascript/async-javascript.php' => 'Async JavaScript',
        'wp-optimize/wp-optimize.php' => 'WP-Optimize',
        'swift-performance-lite/performance.php' => 'Swift Performance Lite',
        'comet-cache/comet-cache.php' => 'Comet Cache',
        'breeze/breeze.php' => 'Breeze',
        'speedycache/speedycache.php' => 'SpeedyCache',
        'w3-total-cache/w3-total-cache.php' => 'W3 Total Cache (SEO Features)',

        // Image optimization
        'shortpixel-image-optimiser/wp-shortpixel.php' => 'ShortPixel Image Optimizer',
        'imagify/imagify.php' => 'Imagify',
        'wp-smushit/wp-smush.php' => 'Smush',
        'ewww-image-optimizer/ewww-image-optimizer.php' => 'EWWW Image Optimizer',
        'optimole-wp/optimole-wp.php' => 'Optimole',
        'tiny-compress-images/tiny-compress-images.php' => 'TinyPNG',
        'webp-express/webp-express.php' => 'WebP Express',
        'converter-for-media/converter-for-media.php' => 'Converter for Media',
        're-smush-it/resmushit.php' => 'reSmush.it Image Optimizer',
        'robin-image-optimizer/robin-image-optimizer.php' => 'Robin Image Optimizer',
    ];

    /**
     * Cache/asset competitors that conflict with ProRank runtime performance
     * features but should not block standalone image optimization.
     *
     * @var array<string, string>
     */
    private static array $cache_asset_competitor_plugins = [
        'wp-rocket/wp-rocket.php' => 'WP Rocket',
        'litespeed-cache/litespeed-cache.php' => 'LiteSpeed Cache',
        'wp-super-cache/wp-cache.php' => 'WP Super Cache',
        'wp-fastest-cache/wpFastestCache.php' => 'WP Fastest Cache',
        'cache-enabler/cache-enabler.php' => 'Cache Enabler',
        'autoptimize/autoptimize.php' => 'Autoptimize',
        'hummingbird-performance/wp-hummingbird.php' => 'Hummingbird',
        'sg-cachepress/sg-cachepress.php' => 'SiteGround Optimizer',
        'nitropack/nitropack.php' => 'NitroPack',
        'perfmatters/perfmatters.php' => 'Perfmatters',
        'flying-press/flying-press.php' => 'FlyingPress',
        'flying-scripts/flying-scripts.php' => 'Flying Scripts',
        'asset-cleanup/asset-cleanup.php' => 'Asset CleanUp',
        'asset-cleanup-pro/asset-cleanup.php' => 'Asset CleanUp Pro',
        'async-javascript/async-javascript.php' => 'Async JavaScript',
        'wp-optimize/wp-optimize.php' => 'WP-Optimize',
        'swift-performance-lite/performance.php' => 'Swift Performance Lite',
        'comet-cache/comet-cache.php' => 'Comet Cache',
        'breeze/breeze.php' => 'Breeze',
        'speedycache/speedycache.php' => 'SpeedyCache',
        'w3-total-cache/w3-total-cache.php' => 'W3 Total Cache (SEO Features)',
    ];

    /**
     * Image-optimization competitors that should suppress ProRank's image
     * optimization module specifically.
     *
     * @var array<string, string>
     */
    private static array $image_optimization_competitor_plugins = [
        'shortpixel-image-optimiser/wp-shortpixel.php' => 'ShortPixel Image Optimizer',
        'imagify/imagify.php' => 'Imagify',
        'wp-smushit/wp-smush.php' => 'Smush',
        'ewww-image-optimizer/ewww-image-optimizer.php' => 'EWWW Image Optimizer',
        'optimole-wp/optimole-wp.php' => 'Optimole',
        'tiny-compress-images/tiny-compress-images.php' => 'TinyPNG',
        'webp-express/webp-express.php' => 'WebP Express',
        'converter-for-media/converter-for-media.php' => 'Converter for Media',
        're-smush-it/resmushit.php' => 'reSmush.it Image Optimizer',
        'robin-image-optimizer/robin-image-optimizer.php' => 'Robin Image Optimizer',
    ];

    /**
     * Determine if SEO conflict safe mode should be enabled.
     *
     * Safe mode prevents duplicate SEO output when multiple SEO plugins are active.
     *
     * @return bool
     */
    public function should_enable_seo_safe_mode(): bool {
        if (!$this->has_active_seo_competitors()) {
            return false;
        }

        $settings = get_option('prorank_conflict_settings', []);
        $enabled = true;

        if (is_array($settings) && array_key_exists('seo_safe_mode', $settings)) {
            $enabled = (bool) $settings['seo_safe_mode'];
        }

        return (bool) apply_filters(
            'prorank_enable_seo_conflict_safe_mode',
            $enabled,
            $this->get_active_seo_competitors_details()
        );
    }

    /**
     * Determine if performance conflict safe mode should be enabled.
     *
     * Safe mode prevents duplicate cache/minify/lazy-load/image optimization
     * behavior when multiple performance plugins are active.
     *
     * @return bool
     */
    public function should_enable_performance_safe_mode(): bool {
        if (!$this->has_active_performance_competitors()) {
            return false;
        }

        $settings = get_option('prorank_conflict_settings', []);
        $enabled = true;

        if (is_array($settings) && array_key_exists('performance_safe_mode', $settings)) {
            $enabled = (bool) $settings['performance_safe_mode'];
        }

        return (bool) apply_filters(
            'prorank_enable_performance_conflict_safe_mode',
            $enabled,
            $this->get_active_performance_competitors_details()
        );
    }
    
    /**
     * Determine if internal linking safe mode should be enabled.
     *
     * Suppresses ProRank internal linking when a competing link plugin is active.
     *
     * @return bool
     */
    public function should_enable_internal_linking_safe_mode(): bool {
        if (!$this->has_active_internal_linking_competitors()) {
            return false;
        }

        $settings = get_option('prorank_conflict_settings', []);
        $enabled = true;

        if (is_array($settings) && array_key_exists('internal_linking_safe_mode', $settings)) {
            $enabled = (bool) $settings['internal_linking_safe_mode'];
        }

        return (bool) apply_filters(
            'prorank_enable_internal_linking_conflict_safe_mode',
            $enabled,
            $this->get_active_internal_linking_competitors()
        );
    }

    /**
     * Check if any internal linking competitor is active.
     *
     * @return bool
     */
    public function has_active_internal_linking_competitors(): bool {
        return !empty($this->get_active_internal_linking_competitors());
    }

    /**
     * Get active internal linking competitors.
     *
     * @return array<string>
     */
    public function get_active_internal_linking_competitors(): array {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$internal_linking_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = $plugin_name;
            }
        }

        return $active;
    }

    /**
     * Get active competitor plugins
     *
     * @return array<string> Array of active competitor plugin names
     */
    public function get_active_competitors(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $active_competitors = [];
        
        foreach (self::$competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active_competitors[] = $plugin_name;
            }
        }
        
        return $active_competitors;
    }

    /**
     * Get active SEO competitors that can duplicate ProRank SEO output.
     *
     * @return array<string>
     */
    public function get_active_seo_competitors(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$seo_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = $plugin_name;
            }
        }

        return $active;
    }

    /**
     * Get active performance competitors that can duplicate optimization behavior.
     *
     * @return array<string>
     */
    public function get_active_performance_competitors(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$performance_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = $plugin_name;
            }
        }

        return $active;
    }

    /**
     * Get active cache/asset competitors.
     *
     * @return array<string>
     */
    public function get_active_cache_asset_competitors(): array {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$cache_asset_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = $plugin_name;
            }
        }

        return $active;
    }

    /**
     * Get active image-optimization competitors.
     *
     * @return array<string>
     */
    public function get_active_image_optimization_competitors(): array {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$image_optimization_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = $plugin_name;
            }
        }

        return $active;
    }
    
    /**
     * Get active competitor plugins with details
     *
     * @return array Array of active competitor details
     */
    public function get_active_competitors_details(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        
        $active_competitors = [];
        
        foreach (self::$competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active_competitors[] = [
                    'name' => $plugin_name,
                    'file' => $plugin_file,
                    'deactivate_url' => wp_nonce_url(
                        admin_url('plugins.php?action=deactivate&plugin=' . urlencode($plugin_file)),
                        'deactivate-plugin_' . $plugin_file
                    )
                ];
            }
        }
        
        return $active_competitors;
    }

    /**
     * Get active SEO competitor details.
     *
     * @return array<int,array{name:string,file:string,deactivate_url:string}>
     */
    public function get_active_seo_competitors_details(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$seo_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = [
                    'name' => $plugin_name,
                    'file' => $plugin_file,
                    'deactivate_url' => wp_nonce_url(
                        admin_url('plugins.php?action=deactivate&plugin=' . urlencode($plugin_file)),
                        'deactivate-plugin_' . $plugin_file
                    ),
                ];
            }
        }

        return $active;
    }

    /**
     * Get active performance competitor details.
     *
     * @return array<int,array{name:string,file:string,deactivate_url:string}>
     */
    public function get_active_performance_competitors_details(): array {
        // Ensure plugin functions are available
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $active = [];
        foreach (self::$performance_competitor_plugins as $plugin_file => $plugin_name) {
            if (is_plugin_active($plugin_file)) {
                $active[] = [
                    'name' => $plugin_name,
                    'file' => $plugin_file,
                    'deactivate_url' => wp_nonce_url(
                        admin_url('plugins.php?action=deactivate&plugin=' . urlencode($plugin_file)),
                        'deactivate-plugin_' . $plugin_file
                    ),
                ];
            }
        }

        return $active;
    }
    
    /**
     * Check if any competitor is active
     *
     * @return bool True if at least one competitor is active
     */
    public function has_active_competitors(): bool {
        return !empty($this->get_active_competitors());
    }

    /**
     * Check if any SEO competitor is active.
     *
     * @return bool
     */
    public function has_active_seo_competitors(): bool {
        return !empty($this->get_active_seo_competitors());
    }

    /**
     * Check if any performance competitor is active.
     *
     * @return bool
     */
    public function has_active_performance_competitors(): bool {
        return !empty($this->get_active_performance_competitors());
    }

    /**
     * Check if any cache/asset competitor is active.
     *
     * @return bool
     */
    public function has_active_cache_asset_competitors(): bool {
        return !empty($this->get_active_cache_asset_competitors());
    }

    /**
     * Check if any image-optimization competitor is active.
     *
     * @return bool
     */
    public function has_active_image_optimization_competitors(): bool {
        return !empty($this->get_active_image_optimization_competitors());
    }

    /**
     * Determine which ProRank performance modules should be suppressed when
     * performance safe mode is active.
     *
     * @return array<int,string>
     */
    public function get_performance_safe_mode_suppressions(): array {
        $suppressed = [];

        if ($this->is_plugin_file_active('wp-rocket/wp-rocket.php')) {
            $suppressed = array_merge($suppressed, $this->get_wp_rocket_safe_mode_suppressions());
        }

        if ($this->is_plugin_file_active('perfmatters/perfmatters.php')) {
            $suppressed = array_merge($suppressed, $this->get_perfmatters_safe_mode_suppressions());
        }

        if ($this->has_active_unprofiled_cache_asset_competitors()) {
            $suppressed = array_merge($suppressed, $this->get_default_cache_asset_suppressions());
        }

        if ($this->has_active_image_optimization_competitors()) {
            $suppressed[] = 'image_optimization';
        }

        return array_values(array_unique($suppressed));
    }

    /**
     * Broad suppressions for cache/asset plugins we do not profile individually.
     *
     * @return array<int,string>
     */
    private function get_default_cache_asset_suppressions(): array {
        return [
            'cache',
            'modern_cache',
            'browser_cache',
            'cache_preload',
            'resource_hints',
            'speculation_rules',
            'css_opt',
            'js_opt',
            'lazyload',
            'critical_css',
            'unused_css',
            'js_minify',
            'html_minify',
            'partytown',
            'inp_optimizer',
            'lcp_beacon',
            'lcp_optimizer',
            'font_optimization',
            'font_subsetting',
            'heartbeat_control',
            'database_optimization',
        ];
    }

    /**
     * Whether any active cache/asset competitor lacks a dedicated feature map.
     *
     * @return bool
     */
    private function has_active_unprofiled_cache_asset_competitors(): bool {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        foreach (self::$cache_asset_competitor_plugins as $plugin_file => $plugin_name) {
            unset($plugin_name);
            if (!is_plugin_active($plugin_file)) {
                continue;
            }

            if (in_array($plugin_file, ['wp-rocket/wp-rocket.php', 'perfmatters/perfmatters.php'], true)) {
                continue;
            }

            return true;
        }

        return false;
    }

    /**
     * Feature-aware suppressions for WP Rocket.
     *
     * @return array<int,string>
     */
    private function get_wp_rocket_safe_mode_suppressions(): array {
        $settings = get_option('wp_rocket_settings', []);
        if (!is_array($settings)) {
            $settings = [];
        }

        $suppressed = [
            'cache',
            'modern_cache',
            'browser_cache',
            'cache_preload',
        ];

        if (
            $this->is_truthy($settings['minify_concatenate_css'] ?? null)
            || $this->is_truthy($settings['minify_css'] ?? null)
            || $this->is_truthy($settings['async_css'] ?? null)
        ) {
            $suppressed[] = 'css_opt';
        }

        if ($this->is_truthy($settings['critical_css'] ?? null)) {
            $suppressed[] = 'critical_css';
        }

        if (
            $this->is_truthy($settings['defer_all_js'] ?? null)
            || $this->is_truthy($settings['delay_js'] ?? null)
        ) {
            $suppressed[] = 'js_opt';
        }

        if ($this->is_truthy($settings['minify_js'] ?? null)) {
            $suppressed[] = 'js_minify';
        }

        if (
            $this->is_truthy($settings['lazyload'] ?? null)
            || $this->is_truthy($settings['lazyload_iframes'] ?? null)
            || $this->is_truthy($settings['lazyload_youtube'] ?? null)
            || $this->is_truthy($settings['lazyload_css_bg_img'] ?? null)
        ) {
            $suppressed[] = 'lazyload';
        }

        if (
            $this->is_truthy($settings['host_fonts_locally'] ?? null)
            || $this->is_truthy($settings['minify_google_fonts'] ?? null)
        ) {
            $suppressed[] = 'font_optimization';
        }

        if (
            $this->is_truthy($settings['auto_preload_fonts'] ?? null)
            || $this->is_truthy($settings['preload_links'] ?? null)
        ) {
            $suppressed[] = 'resource_hints';
        }

        if ($this->is_truthy($settings['preload_links'] ?? null)) {
            $suppressed[] = 'speculation_rules';
        }

        if ($this->is_truthy($settings['control_heartbeat'] ?? null)) {
            $suppressed[] = 'heartbeat_control';
        }

        if ($this->is_truthy($settings['schedule_automatic_cleanup'] ?? null)) {
            $suppressed[] = 'database_optimization';
        }

        return array_values(array_unique($suppressed));
    }

    /**
     * Feature-aware suppressions for Perfmatters.
     *
     * @return array<int,string>
     */
    private function get_perfmatters_safe_mode_suppressions(): array {
        $settings = get_option('perfmatters_options', []);
        if (!is_array($settings)) {
            $settings = [];
        }

        $suppressed = [];

        if (
            $this->is_truthy($this->get_nested_setting($settings, ['assets', 'defer_js']))
            || $this->is_truthy($this->get_nested_setting($settings, ['assets', 'delay_js']))
            || $this->is_truthy($this->get_nested_setting($settings, ['assets', 'delay_all_js']))
            || $this->get_nested_setting($settings, ['assets', 'delay_js_behavior']) === 'all'
        ) {
            $suppressed[] = 'js_opt';
        }

        if ($this->is_truthy($this->get_nested_setting($settings, ['assets', 'minify_js']))) {
            $suppressed[] = 'js_minify';
        }

        if ($this->is_truthy($this->get_nested_setting($settings, ['assets', 'minify_css']))) {
            $suppressed[] = 'css_opt';
        }

        if ($this->is_truthy($this->get_nested_setting($settings, ['assets', 'remove_unused_css']))) {
            $suppressed[] = 'unused_css';
        }

        if (
            $this->is_truthy($this->get_nested_setting($settings, ['lazyload', 'lazy_loading']))
            || $this->is_truthy($this->get_nested_setting($settings, ['lazyload', 'lazy_loading_iframes']))
            || $this->is_truthy($this->get_nested_setting($settings, ['lazyload', 'youtube_preview_thumbnails']))
            || $this->is_truthy($this->get_nested_setting($settings, ['lazyload', 'css_background_images']))
        ) {
            $suppressed[] = 'lazyload';
        }

        if (
            $this->is_truthy($this->get_nested_setting($settings, ['fonts', 'local_google_fonts']))
            || $this->is_truthy($this->get_nested_setting($settings, ['fonts', 'display_swap']))
        ) {
            $suppressed[] = 'font_optimization';
        }

        if ($this->is_truthy($this->get_nested_setting($settings, ['preload', 'critical_images']))) {
            $suppressed[] = 'lcp_optimizer';
            $suppressed[] = 'lcp_beacon';
        }

        if ($this->is_truthy($settings['disable_heartbeat'] ?? null)) {
            $suppressed[] = 'heartbeat_control';
        }

        return array_values(array_unique($suppressed));
    }

    /**
     * Check whether a plugin file is active.
     *
     * @param string $plugin_file
     * @return bool
     */
    private function is_plugin_file_active(string $plugin_file): bool {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        return is_plugin_active($plugin_file);
    }

    /**
     * Fetch a nested setting path from an array.
     *
     * @param array<string,mixed> $settings
     * @param array<int,string> $path
     * @return mixed
     */
    private function get_nested_setting(array $settings, array $path) {
        $value = $settings;
        foreach ($path as $segment) {
            if (!is_array($value) || !array_key_exists($segment, $value)) {
                return null;
            }
            $value = $value[$segment];
        }

        return $value;
    }

    /**
     * Normalize mixed option values to booleans.
     *
     * @param mixed $value
     * @return bool
     */
    private function is_truthy($value): bool {
        if (is_bool($value)) {
            return $value;
        }

        if (is_int($value) || is_float($value)) {
            return (int) $value !== 0;
        }

        if (is_string($value)) {
            return in_array(strtolower(trim($value)), ['1', 'true', 'yes', 'on', 'enabled', 'allow_posts', 'all'], true);
        }

        return !empty($value);
    }
    
    /**
     * Get competitor count
     *
     * @return int Number of active competitor plugins
     */
    public function get_competitor_count(): int {
        return count($this->get_active_competitors());
    }
    
    /**
     * Check if a specific competitor is active
     *
     * @param string $plugin_slug Plugin slug (e.g., 'wordpress-seo', 'rank-math')
     * @return bool True if the competitor is active
     */
    public function is_competitor_active(string $plugin_slug): bool {
        $active_competitors = $this->get_active_competitors();
        
        // Check by plugin name
        foreach (self::$competitor_plugins as $plugin_file => $plugin_name) {
            if (strpos($plugin_file, $plugin_slug) !== false && in_array($plugin_name, $active_competitors, true)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * Get all known competitor plugins
     *
     * @return array<string, string> Map of plugin files to names
     */
    public static function get_all_competitors(): array {
        return self::$competitor_plugins;
    }
    
    /**
     * Get warning message for active competitors
     *
     * @return string|null Warning message or null if no competitors
     */
    public function get_warning_message(): ?string {
        $active_competitors = $this->get_active_competitors();
        
        if (empty($active_competitors)) {
            return null;
        }
        
        $count = count($active_competitors);
        
        if ($count === 1) {
            return sprintf(
/* translators: %1$: value */
                __('Warning: %1$s is currently active. Running multiple SEO or performance optimization plugins can cause conflicts. Consider deactivating it before using ProRank SEO.', 'prorank-seo'),
                $active_competitors[0]
            );
        }
        
        return sprintf(
/* translators: %1$: value, %2$: value */
            __('Warning: %1$d SEO or performance optimization plugins are currently active (%2$s). Running multiple optimization plugins can cause conflicts. Consider deactivating them before using ProRank SEO.', 'prorank-seo'),
            $count,
            implode(', ', $active_competitors)
        );
    }
    
    /**
     * Get health check data
     *
     * @return array Health check information
     */
    public function get_health_check_data(): array {
        $active_competitors = $this->get_active_competitors();
        $has_conflicts = !empty($active_competitors);
        
        return [
            'status' => $has_conflicts ? 'warning' : 'good',
            'label' => $has_conflicts 
                ? __('Potential optimization plugin conflicts detected', 'prorank-seo')
                : __('No optimization plugin conflicts', 'prorank-seo'),
            'description' => $has_conflicts
                ? $this->get_warning_message()
                : __('No other SEO or performance optimization plugins detected. ProRank SEO can run without conflicts.', 'prorank-seo'),
            'competitors' => $active_competitors,
            'count' => count($active_competitors),
            'test' => 'prorank_seo_competitor_check',
        ];
    }
}
