<?php
/**
 * Resource Registry — scans abilities for 'uri' in meta to determine MCP resources.
 *
 * @package AtlasAiDev\Awfah\Resources
 */

namespace AtlasAiDev\Awfah\Resources;

use AtlasAiDev\Awfah\Plugin;

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

class Resource_Registry {

	/**
	 * Static cache (request-scoped).
	 *
	 * @var string[]|null
	 */
	private static ?array $cache = null;

	/**
	 * Get ability IDs that qualify as MCP resources.
	 *
	 * An ability qualifies if its meta contains a non-empty 'uri' key.
	 * Only abilities from enabled modules are included.
	 *
	 * @return string[] Ability IDs (e.g. 'awfah-posts/wp-posts-search').
	 */
	public static function get_resource_ability_ids(): array {
		if ( null !== self::$cache ) {
			return self::$cache;
		}

		$resource_ids     = [];
		$settings         = Plugin::get_settings();
		$module_class_map = Plugin::get_module_class_map();

		// Scan plugin's own ability classes for uri in meta.
		foreach ( $module_class_map as $module_key => $classes ) {
			// Skip disabled modules.
			if ( empty( $settings['modules'][ $module_key ] ) ) {
				continue;
			}

			// Skip store_manager when WooCommerce is not active.
			if ( 'store_manager' === $module_key && ! class_exists( 'WooCommerce' ) ) {
				continue;
			}

			foreach ( $classes as $class ) {
				if ( ! method_exists( $class, 'get_abilities' ) ) {
					continue;
				}

				foreach ( $class::get_abilities() as $ability ) {
					$meta = $ability['meta'] ?? [];
					if ( ! empty( $meta['uri'] ) && is_string( $meta['uri'] ) ) {
						$resource_ids[] = $ability['id'];
					}
				}
			}
		}

		// Include external abilities that have a uri in their meta (Pro only).
		if ( ! empty( $settings['modules']['external_abilities'] ) && apply_filters( 'awfah_enable_external_abilities', false ) ) {
			foreach ( Plugin::get_external_abilities() as $ext ) {
				$meta = $ext['meta'] ?? [];
				if ( ! empty( $meta['uri'] ) && is_string( $meta['uri'] ) ) {
					$resource_ids[] = $ext['id'];
				}
			}
		}

		self::$cache = array_values( array_unique( $resource_ids ) );

		return self::$cache;
	}

	/**
	 * Clear the static cache (useful during testing or after settings change).
	 */
	public static function clear_cache(): void {
		self::$cache = null;
	}
}
