<?php
/**
 * Tool to search WordPress content
 *
 * @package AgenticWP
 * @since 1.0.0
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Search content tool class
 */
class Tool_Search_Content {

	/**
	 * Get the tool schema for OpenAI function calling
	 */
	public static function schema(): array {
		return array(
			'type'        => 'function',
			'name'        => 'search_content',
			'description' => 'Search WordPress posts, pages and custom post types by keyword',
			'strict'      => true,
			'parameters'  => array(
				'type'                 => 'object',
				'properties'           => array(
					'search_term' => array(
						'type'        => 'string',
						'description' => 'The search query to find matching content',
					),
					'post_types'  => array(
						'type'        => 'array',
						'items'       => array( 'type' => 'string' ),
						'description' => 'Specific post types to search, empty array for all public post types',
					),
					'per_page'    => array(
						'type'        => 'integer',
						'description' => 'Number of results to return (1-50), default 10',
					),
				),
				'required'             => array( 'search_term', 'post_types', 'per_page' ),
				'additionalProperties' => false,
			),
		);
	}

	/**
	 * Execute the search
	 *
	 * @param array $args Tool arguments.
	 */
	public static function run( array $args ): string {
		if ( ! class_exists( 'WP_Query' ) || ! function_exists( 'get_post_types' ) ) {
			return 'ERROR: wp_functions_unavailable';
		}

		$search_term = trim( (string) ( $args['search_term'] ?? '' ) );
		if ( '' === $search_term ) {
			return 'ERROR: missing_search_term';
		}

		$per_page = isset( $args['per_page'] ) ? (int) $args['per_page'] : 10;
		if ( $per_page < 1 || $per_page > 50 ) {
			return 'ERROR: invalid_per_page';
		}

		$public_post_types = get_post_types(
			array(
				'public'              => true,
				'exclude_from_search' => false,
			),
			'names'
		);

		$excluded_types    = array( 'attachment', 'revision', 'nav_menu_item' );
		$search_post_types = array_diff( $public_post_types, $excluded_types );

		if ( ! empty( $args['post_types'] ) && is_array( $args['post_types'] ) ) {
			$requested_types   = array_map( 'sanitize_text_field', $args['post_types'] );
			$search_post_types = array_intersect( $search_post_types, $requested_types );
		}

		$query_args = array(
			's'                      => sanitize_text_field( $search_term ),
			'post_type'              => $search_post_types,
			'post_status'            => 'publish',
			'posts_per_page'         => $per_page,
			'no_found_rows'          => false,
			'update_post_meta_cache' => false,
		);

		$query   = new \WP_Query( $query_args );
		$results = array();

		while ( $query->have_posts() ) {
			$query->the_post();
			$results[] = array(
				'id'      => get_the_ID(),
				'title'   => get_the_title(),
				'excerpt' => get_the_excerpt(),
				'type'    => get_post_type(),
				'url'     => get_permalink(),
			);
		}

		wp_reset_postdata();

		return wp_json_encode(
			array(
				'success' => true,
				'found'   => $query->found_posts,
				'results' => $results,
			)
		);
	}
}
