<?php
/**
 * Action Scheduler Search Tool.
 *
 * Search for scheduled actions by keyword with partial matching on hook names.
 * Supports filtering by status and group with pagination.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://agenistrator.com/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Action_Scheduler_Search_Tool class.
 */
class Action_Scheduler_Search_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'search_scheduled_actions';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Search Scheduled Actions', 'agenistrator' );
	}

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Search for scheduled actions by keyword (partial hook name match).';
	}

	/**
	 * Get additional description instructions for the LLM.
	 *
	 * @return string Additional instructions appended to description.
	 * @since     1.0.0
	 */
	public function get_description_instructions() {
		return 'Use this tool when you don\'t know the exact hook name. Returns matching actions with IDs for use with other Action Scheduler tools.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'keyword' => array(
					'type'        => 'string',
					'description' => 'Keyword to search for in hook names (case-insensitive partial match). Examples: "woocommerce", "email", "sync".',
				),
				'limit'   => array(
					'type'        => 'integer',
					'description' => 'Maximum number of results to return (default: 25, max: 100).',
				),
				'offset'  => array(
					'type'        => 'integer',
					'description' => 'Number of matching actions to skip (default: 0).',
				),
			),
			'required'   => array( 'keyword' ),
		);
	}

	/**
	 * Check if the current user can execute this tool.
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return is_super_admin();
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True if the tool only reads data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return true;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The tool arguments.
	 *
	 * @return array The tool execution result.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		if ( ! WordPress_Utils::is_action_scheduler_available() ) {
			return $this->error_response( 'Action Scheduler is not available or not initialized.' );
		}

		$keyword = trim( $args['keyword'] );
		if ( '' === $keyword ) {
			return $this->error_response( 'Keyword cannot be empty.' );
		}

		$limit  = min( max( 1, (int) ( $args['limit'] ?? 25 ) ), 100 );
		$offset = max( 0, (int) ( $args['offset'] ?? 0 ) );

		// Query pending/in-progress actions without hook filter (we'll filter in PHP).
		$query_args = array(
			'status'   => array( 'pending', 'in-progress' ),
			'per_page' => -1, // Fetch all for keyword filtering.
			'orderby'  => 'date',
			'order'    => 'ASC',
		);

		$actions = as_get_scheduled_actions( $query_args, OBJECT );
		$store   = \ActionScheduler::store();
		$pattern = '/' . preg_quote( $keyword, '/' ) . '/i';

		// First pass: count total matches and collect IDs.
		$matching_ids = array();
		foreach ( $actions as $action_id => $action ) {
			if ( preg_match( $pattern, $action->get_hook() ) ) {
				$matching_ids[] = $action_id;
			}
		}

		$total = count( $matching_ids );

		// Apply pagination to matching IDs.
		$paginated_ids = array_slice( $matching_ids, $offset, $limit );

		// Build results for paginated set.
		$results = array();
		foreach ( $paginated_ids as $action_id ) {
			$action       = $actions[ $action_id ];
			$schedule     = $action->get_schedule();
			$scheduled_ts = null;

			if ( $schedule && method_exists( $schedule, 'get_date' ) ) {
				$date = $schedule->get_date();
				if ( $date ) {
					$scheduled_ts = $date->getTimestamp();
				}
			}

			$results[] = array(
				'id'            => $action_id,
				'hook'          => $action->get_hook(),
				'group'         => $action->get_group(),
				'status'        => $store->get_status( $action_id ),
				'next_run'      => $scheduled_ts,
				'next_run_date' => $scheduled_ts ? gmdate( 'Y-m-d H:i:s e', $scheduled_ts ) : null,
			);
		}

		$count = count( $results );

		return $this->success_response(
			0 === $total
				? "No scheduled actions found matching '{$keyword}'"
				: "Found {$total} action(s) matching '{$keyword}'",
			array(
				'keyword'  => $keyword,
				'actions'  => $results,
				'count'    => $count,
				'total'    => $total,
				'limit'    => $limit,
				'offset'   => $offset,
				'has_more' => ( $offset + $count ) < $total,
			)
		);
	}
}
