<?php
/**
 * Compatibility fixes for the legacy AI Services plugin.
 *
 * @package Filter_AI
 */

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

/**
 * Wrap AI Services route-level schema arrays in callbacks.
 *
 * WordPress expects top-level REST route `schema` options to be callable when
 * building the REST index with `context=help`. AI Services 0.7.x registers
 * several schemas as raw arrays, which can fatal in WP-CLI when another plugin
 * (for example WooCommerce) dispatches the REST help index.
 *
 * @param array $endpoints Registered REST endpoints.
 * @return array
 */
function filter_ai_wrap_ai_services_rest_schema_callbacks( $endpoints ) {
	foreach ( $endpoints as $route => $handlers ) {
		if ( ! is_string( $route ) || 0 !== strpos( $route, '/ai-services/v1' ) ) {
			continue;
		}

		if ( ! isset( $handlers['schema'] ) || ! is_array( $handlers['schema'] ) || is_callable( $handlers['schema'] ) ) {
			continue;
		}

		$schema                        = $handlers['schema'];
		$endpoints[ $route ]['schema'] = static function () use ( $schema ) {
			return $schema;
		};
	}

	return $endpoints;
}

if ( function_exists( 'add_filter' ) ) {
	add_filter( 'rest_endpoints', 'filter_ai_wrap_ai_services_rest_schema_callbacks', 99 );
}
