<?php

namespace Calio\Core;

use Calio\Support\ExtensionCatalog;
use Calio\Support\ProAccess;
use Calio\Support\Settings;

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

/**
 * Loads enabled extensions as isolated runtime services.
 */
class ExtensionManager
{
    /**
     * @var array<string, bool>
     */
    private array $booted_extensions = [];

    public function __construct()
    {
        $this->boot_extensions();
        add_action('plugins_loaded', function (): void {
            $this->boot_extensions();
        }, 999);
        add_action('init', function (): void {
            $this->boot_extensions();
        }, 5);
    }

    /**
     * Instantiates each enabled extension class once.
     */
    private function boot_extensions(): void
    {
        foreach (ExtensionCatalog::all() as $slug => $extension) {
            if (!Settings::is_extension_enabled($slug)) {
                continue;
            }

            if (!empty($this->booted_extensions[$slug])) {
                continue;
            }

            if (ProAccess::is_extension_locked($extension)) {
                continue;
            }

            $class_name = (string) ($extension['class'] ?? '');
            if ($class_name === '' || !class_exists($class_name)) {
                continue;
            }

            new $class_name();
            $this->booted_extensions[$slug] = true;
        }
    }
}
