<?php
/**
 * AI Support Gate
 *
 * Site-wide kill-switch for AI features based on WordPress 7.0's
 * wp_supports_ai() function. When wp_supports_ai() returns false the gate
 * returns a 503 WP_Error so every REST handler can halt early without
 * duplicating the logic.
 *
 * @package AIPT\Core\Services
 * @since   2.6.0
 */

declare(strict_types=1);

namespace AIPT\Core\Services;

/**
 * Static guard for the WordPress 7.0 AI kill-switch.
 *
 * Usage (at the top of any AI-generating REST handler):
 *
 *   $ai_gate = \AIPT\Core\Services\AiSupportGate::guard();
 *   if ( $ai_gate instanceof \WP_Error ) {
 *       return $ai_gate;
 *   }
 *
 * @since 2.6.0
 */
final class AiSupportGate {

	/**
	 * Check whether AI features are permitted on this WordPress install.
	 *
	 * Returns null (no-op) when:
	 *   - WordPress < 7.0 (wp_supports_ai() does not exist), or
	 *   - wp_supports_ai() returns true.
	 *
	 * Returns a 503 WP_Error when wp_supports_ai() exists and returns false,
	 * which means WP_AI_SUPPORT is false or the wp_supports_ai filter is
	 * overriding it.
	 *
	 * @since 2.6.0
	 *
	 * @return \WP_Error|null WP_Error on failure, null when AI is permitted.
	 */
	public static function guard(): ?\WP_Error {

		if ( WordPressRuntimeDetector::supportsAi() ) {
			return null;
		}

		return new \WP_Error(
			'aipt_ai_disabled',
			__(
				'AI features are disabled on this site (wp_supports_ai is false). Set WP_AI_SUPPORT to true or remove the filter to re-enable.',
				'ai-product-tools'
			),
			array( 'status' => 503 )
		);
	}
}
