<?php

namespace WPSN\Core;

use WPSN\Modules\AI\AIModule;
use WPSN\Modules\Automation\AutomationModule;
use WPSN\Modules\Bulk\BulkModule;
use WPSN\Modules\BulkTable\BulkTableModule;
use WPSN\Modules\Audit\AuditModule;
use WPSN\Modules\Editor\EditorModule;
use WPSN\Modules\ImportExport\ImportExportModule;
use WPSN\Modules\IndexNow\IndexNowModule;
use WPSN\Modules\ConfigSync\ConfigSyncModule;
use WPSN\Modules\Media\MediaModule;
use WPSN\Modules\AIReadiness\AiReadinessModule;
use WPSN\Modules\MetaTags\MetaTagsModule;
use WPSN\Modules\Redirects\RedirectsModule;
use WPSN\Modules\Robots\RobotsModule;
use WPSN\Modules\Schema\SchemaModule;
use WPSN\Modules\SearchConsole\SearchConsoleModule;
use WPSN\Modules\AutoPilot\AutoPilotModule;
use WPSN\Modules\SchemaValidator\SchemaValidatorModule;
use WPSN\Modules\Sitemap\SitemapModule;
use WPSN\Modules\Social\SocialModule;
use WPSN\Modules\WooCommerce\WooCommerceModule;
use WPSN\Modules\CustomFields\CustomFieldsModule;
use WPSN\Modules\PageBuilders\PageBuildersModule;
use WPSN\Modules\Multisite\MultisiteModule;
use WPSN\Modules\Breadcrumbs\BreadcrumbsModule;
use WPSN\Modules\Privacy\PrivacyModule;
use WPSN\Modules\LocalSEO\LocalSEOModule;
use WPSN\Modules\AuthorSEO\AuthorSEOModule;
use WPSN\Modules\ArchiveControls\ArchiveControlsModule;
use WPSN\Modules\Onboarding\OnboardingModule;
use WPSN\Modules\ActivityLog\ActivityLogModule;
use WPSN\Modules\Analysis\AnalysisModule;
use WPSN\Modules\AdminLists\AdminListsModule;
use WPSN\Modules\Diagnostics\DiagnosticsModule;
use WPSN\Modules\Notifications\NotificationsModule;
use WPSN\Modules\Stability\StabilityModule;
use WPSN\Modules\DriftMonitor\DriftMonitorModule;
use WPSN\Modules\Revisions\RevisionsModule;
use WPSN\Modules\IndexationRisk\IndexationRiskModule;
use WPSN\Modules\Licensing\LicensingModule;
use WPSN\Modules\Licensing\PlanMatrix;
use WPSN\Modules\SaaSSync\SaaSSyncModule;
use WPSN\Modules\SaaSDashboard\SaaSDashboardModule;
use WPSN\Modules\SerpGap\SerpGapModule;
use WPSN\Modules\ContentClusters\ContentClustersModule;
use WPSN\Modules\CrawlBudget\CrawlBudgetModule;
use WPSN\Modules\SiteCrawl\SiteCrawlModule;
use WPSN\Modules\Issues\IssuesModule;
use WPSN\Modules\TasksHub\TasksHubModule;
use WPSN\Modules\FrontendInspector\FrontendInspectorModule;
use WPSN\Modules\SearchUrls\SearchUrlsModule;
use WPSN\Modules\HeadCleanup\HeadCleanupModule;
use WPSN\Modules\SiteKit\SiteKitModule;

defined('ABSPATH') || exit;

final class ModuleRegistry
{
    private Container $container;

    /** @var array<string, ModuleInterface> */
    private array $modules = [];

    public function __construct(Container $container)
    {
        $this->container = $container;

        $classes = [
            'meta_tags' => MetaTagsModule::class,
            'social' => SocialModule::class,
            'woocommerce' => WooCommerceModule::class,
            'local_seo' => LocalSEOModule::class,
            'author_seo' => AuthorSEOModule::class,
            'archive_controls' => ArchiveControlsModule::class,
            'analysis' => AnalysisModule::class,
            // Integrations
            'page_builders' => PageBuildersModule::class,
            'custom_fields' => CustomFieldsModule::class,
            'multisite' => MultisiteModule::class,
            'site_kit' => SiteKitModule::class,
            'schema' => SchemaModule::class,
            'sitemap' => SitemapModule::class,
            'robots' => RobotsModule::class,
            'redirects' => RedirectsModule::class,
            'audit' => AuditModule::class,
            'editor' => EditorModule::class,
            'admin_lists' => AdminListsModule::class,
            'import_export' => ImportExportModule::class,
            'config_sync' => ConfigSyncModule::class,
            'indexnow' => IndexNowModule::class,
            'bulk' => BulkModule::class,
            'bulk_table' => BulkTableModule::class,
            'media' => MediaModule::class,
            'ai_readiness' => AiReadinessModule::class,
            'ai' => AIModule::class,
            'automation' => AutomationModule::class,
            'search_console' => SearchConsoleModule::class,
            'autopilot' => AutoPilotModule::class,
            // Content & crawl (unique features)
            'content_clusters' => ContentClustersModule::class,
            'crawl_budget' => CrawlBudgetModule::class,
            'site_crawl' => SiteCrawlModule::class,
            'issues' => IssuesModule::class,
            'tasks_hub' => TasksHubModule::class,
            'schema_validator' => SchemaValidatorModule::class,
            'frontend_inspector' => FrontendInspectorModule::class,
            'breadcrumbs' => BreadcrumbsModule::class,
            'search_urls' => SearchUrlsModule::class,
            'head_cleanup' => HeadCleanupModule::class,
            'activity_log' => ActivityLogModule::class,
            'privacy' => PrivacyModule::class,
            'onboarding' => OnboardingModule::class,
            'diagnostics' => DiagnosticsModule::class,
            'notifications' => NotificationsModule::class,
            'stability' => StabilityModule::class,
            'drift_monitor' => DriftMonitorModule::class,
            'revisions' => RevisionsModule::class,
            'indexation_risk' => IndexationRiskModule::class,
            // Monetization / Pro gating (optional)
            'licensing' => LicensingModule::class,
            'saas_sync' => SaaSSyncModule::class,
            'saas_dashboard' => SaaSDashboardModule::class,
            // SERP gap analyzer (providers are pluggable)
            'serp_gap' => SerpGapModule::class,
        ];

        $buildTier = PlanMatrix::buildTier();

        foreach ($classes as $moduleId => $class) {
            if (!PlanMatrix::buildAllowsModule((string) $moduleId, $buildTier)) {
                continue;
            }

            if (!class_exists($class)) {
                continue;
            }

            /** @var ModuleInterface $module */
            $module = new $class($container);
            $this->modules[$module->id()] = $module;
        }
    }

    /**
     * @return array<string, ModuleInterface>
     */
    public function all(): array
    {
        return $this->modules;
    }

    public function isEnabled(string $moduleId): bool
    {
        if (!isset($this->modules[$moduleId])) {
            return false;
        }
        $module = $this->modules[$moduleId];

        $enabled = $this->container->get('settings')->moduleEnabled($moduleId, $module->defaultEnabled());

        /**
         * Filter for module enablement.
         *
         * Useful for licensing/entitlements (lock premium modules), environment policies, etc.
         */
        $enabled = (bool) apply_filters('wpsn/module/is_enabled', $enabled, $moduleId, $module);

        return $enabled;
    }

    public function registerEnabled(): void
    {
        foreach ($this->modules as $id => $module) {
            if (!$this->isEnabled($id)) {
                continue;
            }
            $module->register();
        }
    }

    public function bootEnabled(): void
    {
        foreach ($this->modules as $id => $module) {
            if (!$this->isEnabled($id)) {
                continue;
            }
            $module->boot();
        }
    }
}