<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class GetAudiencePrioritiesAbility {

	const ABILITY_NAME = 'aieo/get-audience-priorities';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Get audience priorities', 'ai-eshop-optimizer' ),
				'description'         => __( 'For one AIEO audience key, return the inferred-priority distribution (which priorities matter most to that segment, by heuristic / kNN / embedding source). Pass audience_key=all for the whole base.', '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(
				'audience_key' => array(
					'type'        => 'string',
					'default'     => 'all',
					'description' => 'AIEO audience key (`all`, `guest`, `role:<slug>`, `tier:<id>`). Use `all` to roll up the whole customer base.',
				),
			),
		);
	}

	public static function execute( $input = null ) {
		$input    = is_array( $input ) ? $input : array();
		$audience = isset( $input['audience_key'] ) ? sanitize_text_field( (string) $input['audience_key'] ) : 'all';
		if ( $audience === '' ) { $audience = 'all'; }

		if ( ! class_exists( 'AIEO_DMM_Surveys' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO_DMM_Surveys not available — DMM bootstrap may have failed.', 'ai-eshop-optimizer' ) );
		}

		return \AIEO_DMM_Surveys::get_audience_priority_distribution( $audience );
	}
}
