<?php

declare(strict_types=1);

namespace LolaCore\Admin;

use WP\MCP\Abilities\DiscoverAbilitiesAbility;
use WP\MCP\Abilities\ExecuteAbilityAbility;
use WP\MCP\Abilities\GetAbilityInfoAbility;

/**
 * Registers MCP adapter protocol meta-abilities before the lazy Abilities API init
 * can be triggered by WooCommerce, WPForms, or addon registrars.
 *
 * wp_abilities_api_init fires only once per request. McpAdapter::maybe_create_default_server()
 * hooks register_default_abilities inside rest_api_init@15 — too late when another plugin
 * already called wp_get_abilities() during init. Early registration here fixes that race.
 */
final class McpMetaAbilitiesBootstrap
{
    public static function register(): void
    {
        add_action('wp_abilities_api_categories_init', [self::class, 'registerCategory'], 0);
        add_action('wp_abilities_api_init', [self::class, 'registerAbilities'], 0);
    }

    public static function registerCategory(): void
    {
        if (!function_exists('wp_register_ability_category')) {
            return;
        }

        if (function_exists('wp_has_ability_category') && wp_has_ability_category('mcp-adapter')) {
            return;
        }

        wp_register_ability_category(
            'mcp-adapter',
            [
                'label'       => 'MCP Adapter',
                'description' => 'Abilities for the MCP Adapter',
            ]
        );
    }

    public static function registerAbilities(): void
    {
        if (!function_exists('wp_register_ability')) {
            return;
        }

        if (
            function_exists('wp_has_ability')
            && wp_has_ability('mcp-adapter/discover-abilities')
        ) {
            return;
        }

        if (!class_exists(DiscoverAbilitiesAbility::class)) {
            return;
        }

        DiscoverAbilitiesAbility::register();
        GetAbilityInfoAbility::register();
        ExecuteAbilityAbility::register();
    }
}
