<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BuyProbabilityByEngagementAbility {

	const ABILITY_NAME = 'aieo/buy-probability-by-engagement';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Buy probability by engagement', 'ai-eshop-optimizer' ),
				'description'         => __( 'For one product, return a 16-row bucket table (scroll-depth quartile × time-on-page quartile) with viewers, cart-adders, and empirical P(cart-add) per bucket. Heuristic — pure aggregate, not ML. Use to answer "if a visitor scrolls 75%+ and stays 90s+, how likely are they to buy?".', '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',
			'required'   => array( 'product_id' ),
			'properties' => array(
				'product_id'  => array(
					'type'    => 'integer',
					'minimum' => 1,
				),
				'period_days' => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 730,
					'default' => 90,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input       = is_array( $input ) ? $input : array();
		$product_id  = isset( $input['product_id'] ) ? (int) $input['product_id'] : 0;
		$period_days = isset( $input['period_days'] ) ? (int) $input['period_days'] : 90;
		if ( $product_id <= 0 ) {
			return new \WP_Error( 'aieo_invalid_input', __( 'product_id is required.', 'ai-eshop-optimizer' ) );
		}
		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::compute_bucket_table( $product_id, $period_days );
	}
}
