<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class FindUncoveredProductsAbility {

	const ABILITY_NAME = 'aieo/find-uncovered-products';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Find uncovered products', 'ai-eshop-optimizer' ),
				'description'         => __( 'Return the highest-turnover products that have ZERO `pa_need` taxonomy terms assigned — the priority queue for needs-tagging work. Driven by AIEO temp_orders, so only WC sites with the AIEO order snapshot get rows.', '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(
				'per_page' => array(
					'type'        => 'integer',
					'minimum'     => 1,
					'maximum'     => 200,
					'default'     => 50,
					'description' => 'Max products to return.',
				),
				'category' => array(
					'type'        => 'integer',
					'description' => 'Optional product_cat term_id to filter results to. Defaults to all categories.',
				),
			),
		);
	}

	public static function execute( $input ) {
		$input    = is_array( $input ) ? $input : array();
		$per_page = isset( $input['per_page'] ) ? max( 1, min( 200, (int) $input['per_page'] ) ) : 50;
		$cat_id   = isset( $input['category'] ) ? (int) $input['category'] : 0;

		if ( ! class_exists( 'AIEO_DMM' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO DMM not loaded.', 'ai-eshop-optimizer' ) );
		}

		$module = \AIEO_DMM::instance()->get_module( 'product_needs' );
		if ( ! ( $module instanceof \AIEO_DMM_Product_Needs ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO product_needs module not loaded.', 'ai-eshop-optimizer' ) );
		}
		$result = $module->get_impactful_products_without_needs( $per_page );

		
		
		
		if ( $cat_id > 0 && ! empty( $result['rows'] ) ) {
			$filtered = array();
			foreach ( $result['rows'] as $row ) {
				if ( has_term( $cat_id, 'product_cat', (int) $row['pid'] ) ) {
					$filtered[] = $row;
				}
			}
			$result['rows']           = $filtered;
			$result['category_id']    = $cat_id;
			$result['filtered_count'] = count( $filtered );
		}
		return $result;
	}
}
