<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class RatingConversionCorrelationAbility {

	const ABILITY_NAME = 'aieo/rating-conversion-correlation';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Rating × conversion correlation', 'ai-eshop-optimizer' ),
				'description'         => __( 'Bucket products by their AIEO average star rating (1-2, 2-3, 3-4, 4-5) and compute cart-add rate per bucket — SUM(cart_adds) / SUM(product_views) — to answer "do my higher-rated products convert measurably better?". Joins wp_aieo_rating_stats with wp_aieo_addcart_events and wp_aieo_sessions.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => self::input_schema(),
				'output_schema'       => array( 'type' => 'object' ),
				'execute_callback'    => array( __CLASS__, 'execute' ),
				'permission_callback' => array( __CLASS__, 'permission_check' ),
				'meta'                => array(
					'annotations'  => array(
						'readonly'   => true,
						'idempotent' => true,
					),
					'show_in_rest' => true,
				),
			)
		);
	}

	public static function permission_check( $input = null ) {
		unset( $input );
		return current_user_can( 'manage_woocommerce' );
	}

	private static function input_schema() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'period' => array(
					'type'    => 'string',
					'default' => 'last_30_days',
					'enum'    => PeriodHelper::ALLOWED,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input  = is_array( $input ) ? $input : array();
		$period = isset( $input['period'] ) ? (string) $input['period'] : 'last_30_days';
		if ( ! class_exists( 'AIEO_Session_Attribution_Bridge' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_Session_Attribution_Bridge not loaded.', 'ai-eshop-optimizer' ) );
		}
		return \AIEO_Session_Attribution_Bridge::get_rating_vs_conversion( $period );
	}
}
