<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class FindLookalikesAbility {

	const ABILITY_NAME = 'aieo/find-lookalikes';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Find lookalike customers', 'ai-eshop-optimizer' ),
				'description'         => __( "Given a customer, return the top-N most similar customers by priority-inference distance (same feature vector the nightly k-NN job uses). All identifiers pseudonymous (`Customer #N`).", '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( 'customer_id' ),
			'properties' => array(
				'customer_id' => array(
					'type'    => 'integer',
					'minimum' => 1,
				),
				'n'           => array(
					'type'    => 'integer',
					'minimum' => 1,
					'maximum' => 50,
					'default' => 10,
				),
			),
		);
	}

	public static function execute( $input ) {
		$input   = is_array( $input ) ? $input : array();
		$user_id = isset( $input['customer_id'] ) ? (int) $input['customer_id'] : 0;
		$n       = isset( $input['n'] ) ? (int) $input['n'] : 10;
		if ( $user_id <= 0 ) {
			return new \WP_Error( 'aieo_invalid_input', __( 'customer_id is required.', 'ai-eshop-optimizer' ) );
		}
		if ( ! class_exists( 'AIEO_DMM_Surveys' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_DMM_Surveys not available.', 'ai-eshop-optimizer' ) );
		}
		$neighbours = \AIEO_DMM_Surveys::find_customer_lookalikes( $user_id, $n );
		return array(
			'anchor'      => array(
				'customer_id' => $user_id,
				'pseudonym'   => 'Customer #' . $user_id,
			),
			'neighbours'  => $neighbours,
			'n_requested' => $n,
			'distance'    => 'euclidean on knn_feature_vector',
		);
	}
}
