<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class GetRecoImpressionsAbility {

	const ABILITY_NAME = 'aieo/get-reco-impressions';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Get reco impressions', 'ai-eshop-optimizer' ),
				'description'         => __( 'Per-surface impression counts from `wp_aieo_reco_events` for a period. Use this to see which recommendation rails (same-needs, upsells, cross-sells, related, recently-viewed) are even being seen by shoppers.', '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(
				'period' => array(
					'type'        => 'string',
					'default'     => 'last_7_days',
					'enum'        => PeriodHelper::ALLOWED,
					'description' => 'Time window. Defaults to last_7_days.',
				),
			),
		);
	}

	public static function execute( $input ) {
		global $wpdb;
		$input  = is_array( $input ) ? $input : array();
		$period = PeriodHelper::resolve( $input['period'] ?? 'last_7_days' );
		$table  = $wpdb->prefix . 'aieo_reco_events';

		
		$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 array(
				'period' => $period,
				'rows'   => array(),
				'note'   => __( 'wp_aieo_reco_events not installed yet.', 'ai-eshop-optimizer' ),
			);
		}

		
		$rows = $wpdb->get_results( $wpdb->prepare(
			"SELECT surface,
			        COUNT(*)                                       AS impressions,
			        SUM(event_type = 'reco_click')                 AS clicks,
			        COUNT(DISTINCT session_id)                     AS sessions
			   FROM {$table}
			  WHERE ts BETWEEN %s AND %s
			    AND event_type IN ('impression', 'reco_click')
			  GROUP BY surface
			  ORDER BY impressions DESC",
			$period['since'], $period['until']
		), ARRAY_A );

		$out = array();
		foreach ( (array) $rows as $r ) {
			$impressions = (int) $r['impressions'];
			$clicks      = (int) $r['clicks'];
			$out[] = array(
				'surface'     => (string) $r['surface'],
				'impressions' => $impressions,
				'clicks'      => $clicks,
				'sessions'    => (int) $r['sessions'],
				'ctr'         => $impressions > 0 ? round( $clicks / $impressions, 4 ) : 0.0,
			);
		}

		return array(
			'period' => $period,
			'rows'   => $out,
		);
	}
}
