<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class BrandPerformanceTiersAbility {

	const ABILITY_NAME = 'aieo/brand-performance-tiers';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Brand performance tiers', 'ai-eshop-optimizer' ),
				'description'         => __( 'Bucket every active brand into top / mid / bottom by lifetime revenue (from `wp_aieo_core_brand_vitals.total_sales`). Top 20% = top tier, next 30% = mid, rest = bottom. Use this to triage the brand portfolio.', '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 );
		global $wpdb;
		$table = $wpdb->prefix . 'aieo_core_brand_vitals';
		$exists = (int) $wpdb->get_var( $wpdb->prepare(
			"SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s",
			$table
		) );
		if ( ! $exists ) {
			return new \WP_Error( 'aieo_unavailable', __( 'wp_aieo_core_brand_vitals not installed.', 'ai-eshop-optimizer' ) );
		}

		
		$rows = $wpdb->get_results(
			"SELECT brand_id, brand_name, brand_slug, product_count, total_sales
			   FROM {$table}
			  WHERE product_count > 0
			  ORDER BY total_sales DESC",
			ARRAY_A
		);
		if ( empty( $rows ) ) {
			return array( 'tiers' => array( 'top' => array(), 'mid' => array(), 'bottom' => array() ), 'total_brands' => 0 );
		}

		$total       = count( $rows );
		$top_cutoff  = (int) ceil( $total * 0.2 );
		$mid_cutoff  = $top_cutoff + (int) ceil( $total * 0.3 );

		$tiers = array( 'top' => array(), 'mid' => array(), 'bottom' => array() );
		foreach ( $rows as $i => $r ) {
			$bucket = $i < $top_cutoff ? 'top' : ( $i < $mid_cutoff ? 'mid' : 'bottom' );
			$tiers[ $bucket ][] = array(
				'brand_id'      => (int) $r['brand_id'],
				'name'          => (string) $r['brand_name'],
				'slug'          => (string) $r['brand_slug'],
				'product_count' => (int) $r['product_count'],
				'total_sales'   => (int) $r['total_sales'],
				'rank'          => $i + 1,
			);
		}

		return array(
			'total_brands' => $total,
			'tier_sizes'   => array(
				'top'    => count( $tiers['top'] ),
				'mid'    => count( $tiers['mid'] ),
				'bottom' => count( $tiers['bottom'] ),
			),
			'tiers'        => $tiers,
		);
	}
}
