<?php

namespace AIEO\Claude\Abilities;

defined( 'ABSPATH' ) || exit;

class DfsRankedKeywordsAbility {

	const ABILITY_NAME = 'aieo/dfs-ranked-keywords';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Ranked keywords (DataForSEO snapshot)', 'ai-eshop-optimizer' ),
				'description'         => __( 'Keywords this site ranks for on Google, from the weekly DataForSEO snapshot (free local read): keyword, position, search volume, ETV, intent, and the page. Filter to one object with object_type + object_id, or get the site-wide list by volume.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array(
					'type'       => 'object',
					'properties' => array(
						'object_type' => array( 'type' => 'string' ),
						'object_id'   => array( 'type' => 'integer', 'minimum' => 1 ),
						'limit'       => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 200, 'default' => 50 ),
					),
				),
				'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' ) || current_user_can( 'manage_options' );
	}

	public static function execute( $input ) {
		global $wpdb;
		$input = is_array( $input ) ? $input : array();
		$limit = isset( $input['limit'] ) ? max( 1, min( 200, (int) $input['limit'] ) ) : 50;
		if ( ! class_exists( 'AIEO_DFS_Rankings' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-dfs-rankings.php';
		}
		if ( ! \AIEO_DFS_Rankings::table_exists() ) {
			return array( 'keywords' => array(), 'hint' => __( 'No rankings snapshot yet — connect DataForSEO and pull (SEO → General).', 'ai-eshop-optimizer' ) );
		}
		$rk = $wpdb->prefix . 'aieo_dfs_rankings';
		if ( ! empty( $input['object_type'] ) && ! empty( $input['object_id'] ) ) {
			
			$rows = $wpdb->get_results( $wpdb->prepare(
				"SELECT keyword, position, volume, etv, intent, url_path FROM `{$rk}` WHERE object_type = %s AND object_id = %d ORDER BY volume DESC, position ASC LIMIT %d",
				sanitize_key( (string) $input['object_type'] ),
				(int) $input['object_id'],
				$limit
			), ARRAY_A );
		} else {
			
			$rows = $wpdb->get_results( $wpdb->prepare(
				"SELECT keyword, position, volume, etv, intent, url_path, object_type, object_id FROM `{$rk}` ORDER BY volume DESC, position ASC LIMIT %d",
				$limit
			), ARRAY_A );
		}
		return array( 'keywords' => is_array( $rows ) ? $rows : array() );
	}
}

class DfsStrikingDistanceAbility {

	const ABILITY_NAME = 'aieo/dfs-striking-distance';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Striking-distance keywords', 'ai-eshop-optimizer' ),
				'description'         => __( 'Keywords ranked 8–20 on Google (one push from page 1 — the highest-ROI optimisation queue), highest volume first, with the page each one belongs to. Free local read of the weekly DataForSEO snapshot.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array(
					'type'       => 'object',
					'properties' => array(
						'limit' => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
					),
				),
				'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' ) || current_user_can( 'manage_options' );
	}

	public static function execute( $input ) {
		$input = is_array( $input ) ? $input : array();
		if ( ! class_exists( 'AIEO_DFS_Rankings' ) ) {
			require_once AIEO_DIR . 'includes/seo/class-aieo-dfs-rankings.php';
		}
		return array( 'striking' => \AIEO_DFS_Rankings::striking_distance( isset( $input['limit'] ) ? (int) $input['limit'] : 20 ) );
	}
}

class ContentVitalsLeaderboardAbility {

	const ABILITY_NAME = 'aieo/content-vitals-leaderboard';

	public static function register() {
		wp_register_ability(
			self::ABILITY_NAME,
			array(
				'label'               => __( 'Content vitals leaderboard', 'ai-eshop-optimizer' ),
				'description'         => __( 'Content (posts, pages, KB entries…) ranked from the daily content-vitals snapshot. order=demand (reach × engagement × recency), order=views (30-day views), or order=decaying (historically popular but fading — refresh candidates). Optional post_type filter.', 'ai-eshop-optimizer' ),
				'category'            => \AIEO\Claude\Bootstrap::CATEGORY,
				'input_schema'        => array(
					'type'       => 'object',
					'properties' => array(
						'order'     => array( 'type' => 'string', 'enum' => array( 'demand', 'views', 'decaying' ), 'default' => 'demand' ),
						'post_type' => array( 'type' => 'string' ),
						'limit'     => array( 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 20 ),
					),
				),
				'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' ) || current_user_can( 'manage_options' );
	}

	public static function execute( $input ) {
		global $wpdb;
		$input = is_array( $input ) ? $input : array();
		$limit = isset( $input['limit'] ) ? max( 1, min( 100, (int) $input['limit'] ) ) : 20;
		$order = isset( $input['order'] ) ? (string) $input['order'] : 'demand';
		$cv    = $wpdb->prefix . 'aieo_core_content_vitals';
		if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $cv ) ) !== $cv ) {
			return array( 'rows' => array(), 'hint' => __( 'Content vitals not built yet (nightly cron).', 'ai-eshop-optimizer' ) );
		}
		$where  = '';
		$params = array();
		if ( ! empty( $input['post_type'] ) ) {
			$where    = ' WHERE post_type = %s';
			$params[] = sanitize_key( (string) $input['post_type'] );
		}
		switch ( $order ) {
			case 'views':
				$order_by = 'views_30d DESC';
				break;
			case 'decaying':
				
				$order_by = '(views_lifetime - views_30d) DESC, views_30d ASC';
				if ( '' === $where ) {
					$where = ' WHERE views_lifetime > views_30d * 3 AND views_lifetime > 30';
				} else {
					$where .= ' AND views_lifetime > views_30d * 3 AND views_lifetime > 30';
				}
				break;
			default:
				$order_by = 'content_demand DESC, views_30d DESC';
		}
		$params[] = $limit;
		
		$rows = $wpdb->get_results( $wpdb->prepare(
			"SELECT post_type, content_id, title, content_url, views_30d, views_lifetime, visitors_30d,
			        avg_time_30d, avg_scroll_30d, engagement_score, content_demand, is_pillar, seo_score
			   FROM `{$cv}`{$where} ORDER BY {$order_by} LIMIT %d",
			...$params
		), ARRAY_A );
		return array( 'order' => $order, 'rows' => is_array( $rows ) ? $rows : array() );
	}
}
