<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class GetCustomerArchetypeAbility {

	const ABILITY_NAME = 'aieo/get-customer-archetype';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Get customer archetype', 'ai-eshop-optimizer' ),
				'description'         => __( "Return one customer's inferred priority profile (the F18-extrapolated archetype) plus supporting signals — price band, discount share, top brand affinity. Returns pseudonymised `Customer #N` only; never real PII.", '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,
					'description' => 'WordPress user ID of the customer to inspect.',
				),
			),
		);
	}

	public static function execute( $input ) {
		$input    = is_array( $input ) ? $input : array();
		$user_id  = isset( $input['customer_id'] ) ? (int) $input['customer_id'] : 0;
		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' ) );
		}
		$profile = \AIEO_DMM_Surveys::get_customer_priority_profile( $user_id );
		if ( $profile === null ) {
			return array(
				'customer_id' => $user_id,
				'pseudonym'   => 'Customer #' . $user_id,
				'note'        => __( 'No customer_intelligence row yet — this customer has not been profiled. Run the nightly recompute.', 'ai-eshop-optimizer' ),
			);
		}
		return $profile;
	}
}
