<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BuyProbabilityLeaderboardAbility {

	const ABILITY_NAME = 'aieo/buy-probability-leaderboard';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Buy-probability leaderboard', 'ai-eshop-optimizer' ),
				'description'         => __( 'Products where cart-add rate among highly engaged visitors (scroll ≥75%, time on page ≥90s) is more than 5× the rate among disengaged visitors (scroll <25%, time <10s). Returns top N products by lift — the catalogue items where UX investment will pay off most.', '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_days' => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 730,
					'default' => 90,
				),
				'limit'       => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 100,
					'default' => 20,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input       = is_array( $input ) ? $input : array();
		$period_days = isset( $input['period_days'] ) ? (int) $input['period_days'] : 90;
		$limit       = isset( $input['limit'] ) ? (int) $input['limit'] : 20;
		if ( ! class_exists( 'AIEO_Conversion_Probability_Model' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_Conversion_Probability_Model not loaded.', 'ai-eshop-optimizer' ) );
		}
		return \AIEO_Conversion_Probability_Model::find_steepest_gradient_products( $period_days, $limit );
	}
}
