<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BrandGiftCoverageAbility {

	const ABILITY_NAME = 'aieo/brand-gift-coverage';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Brand gift coverage', 'ai-eshop-optimizer' ),
				'description'         => __( 'For each active brand, report whether a Brand Gift offer is currently enabled (via `wp_aieo_dmm_brand_gift_offers`) and which brands are uncovered. Use this to spot brands missing a gift hook.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array( 'type' => 'object' ),
				'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' );
	}

	public static function execute( $input = null ) {
		unset( $input );

		if ( ! class_exists( 'AIEO_DMM_Brand_Gifts' ) ) {
			return array( 'covered' => array(), 'uncovered' => array(), 'note' => __( 'Brand Gifts module not loaded.', 'ai-eshop-optimizer' ) );
		}
		$module = \AIEO_DMM_Brand_Gifts::instance();
		if ( ! $module ) {
			return new \WP_Error( 'aieo_unavailable', __( 'Brand Gifts module not initialised.', 'ai-eshop-optimizer' ) );
		}
		$active_offers = $module->get_active_offers();

		
		$covered_brand_ids = array();
		foreach ( (array) $active_offers as $offer ) {
			$bids = isset( $offer['brand_term_ids'] ) && is_array( $offer['brand_term_ids'] )
				? $offer['brand_term_ids']
				: array();
			foreach ( $bids as $bid ) {
				$bid = (int) $bid;
				if ( $bid > 0 ) { $covered_brand_ids[ $bid ] = true; }
			}
		}

		
		$covered   = array();
		$uncovered = array();
		if ( class_exists( 'AIEO_Core_Brand_Vitals' ) ) {
			$cbv      = \AIEO_Core_Brand_Vitals::instance();
			$all      = $cbv->get_all_grouped();
			$emitted  = array();
			foreach ( $all as $bucket ) {
				foreach ( (array) ( $bucket['brands'] ?? array() ) as $b ) {
					$tid = (int) ( $b['term_id'] ?? 0 );
					if ( $tid <= 0 || isset( $emitted[ $tid ] ) ) { continue; }
					$emitted[ $tid ] = true;
					$row = array(
						'brand_id'      => $tid,
						'name'          => (string) ( $b['name'] ?? '' ),
						'slug'          => (string) ( $b['slug'] ?? '' ),
						'product_count' => (int) ( $b['product_count'] ?? 0 ),
						'total_sales'   => (int) ( $b['total_sales'] ?? 0 ),
					);
					if ( isset( $covered_brand_ids[ $tid ] ) ) {
						$covered[] = $row;
					} else {
						$uncovered[] = $row;
					}
				}
			}
		}

		
		
		usort( $uncovered, static function ( $a, $b ) { return $b['total_sales'] <=> $a['total_sales']; } );

		return array(
			'active_offers_count' => count( (array) $active_offers ),
			'covered_count'       => count( $covered ),
			'uncovered_count'     => count( $uncovered ),
			'covered'             => $covered,
			'uncovered'           => array_slice( $uncovered, 0, 50 ),
		);
	}
}
