<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class ListAudiencesAbility {

	const ABILITY_NAME = 'aieo/list-audiences';

	
	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'List audiences', 'ai-eshop-optimizer' ),
				'description'         => __( 'List the AIEO audience segments configured on this store (guest, per-role, per-loyalty-tier) with sizes and labels. Requires the AI eShop Optimizer plugin.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array( 'type' => 'object' ),
				'output_schema'       => self::output_schema(),
				'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 output_schema() {
		return array( 'type' => 'object' );
	}

	
	public static function execute( $input = null ) {
		unset( $input );
		if ( ! class_exists( 'AIEO_Identity_Bridge' ) ) {
			return new \WP_Error( 'aieo_unavailable', __( 'AIEO Identity Bridge is not loaded.', 'ai-eshop-optimizer' ) );
		}

		global $wpdb;
		$keys = \AIEO_Identity_Bridge::known_audience_keys();

		
		
		
		$audiences = array();
		foreach ( $keys as $key ) {
			$size = null;
			if ( strpos( $key, 'tier:' ) === 0 || strpos( $key, 'role:' ) === 0 ) {
				$size = (int) $wpdb->get_var(
					$wpdb->prepare(
						"SELECT COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = %s AND meta_value = %s",
						\AIEO_Identity_Bridge::META_AUDIENCE,
						$key
					)
				);
			}

			$audiences[] = array(
				'audience_key' => $key,
				'kind'         => self::kind_for_key( $key ),
				'label'        => self::label_for_key( $key ),
				'size'         => $size,
			);
		}

		return array(
			'audiences' => $audiences,
			'note'      => __( 'guest size is intentionally null — anonymous traffic is not stamped with a user-meta audience.', 'ai-eshop-optimizer' ),
		);
	}

	private static function kind_for_key( $key ) {
		if ( $key === 'guest' )                    { return 'guest'; }
		if ( strpos( $key, 'tier:' ) === 0 )       { return 'loyalty_tier'; }
		if ( strpos( $key, 'role:' ) === 0 )       { return 'role'; }
		return 'unknown';
	}

	private static function label_for_key( $key ) {
		if ( $key === 'guest' ) { return __( 'Guest / not logged in', 'ai-eshop-optimizer' ); }
		if ( strpos( $key, 'role:' ) === 0 ) {
			$slug = substr( $key, 5 );
			$roles = function_exists( 'wp_roles' ) ? wp_roles() : null;
			if ( $roles && isset( $roles->role_names[ $slug ] ) ) {
				return (string) translate_user_role( $roles->role_names[ $slug ] );
			}
			return $slug;
		}
		if ( strpos( $key, 'tier:' ) === 0 ) {
			global $wpdb;
			$id  = (int) substr( $key, 5 );
			$tbl = $wpdb->prefix . 'aieo_dmm_loyalty_classes';
			
			$name = $wpdb->get_var( $wpdb->prepare( "SELECT name FROM {$tbl} WHERE id = %d", $id ) );
			return is_string( $name ) && $name !== '' ? $name : 'Tier #' . $id;
		}
		return $key;
	}
}
