<?php
/**
 * List Pages Tool.
 *
 * Allows the agent to retrieve lists of WordPress pages with filtering options
 * including status, parent, pagination, and ordering.
 *
 * @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;
}

/**
 * List_Pages_Tool class.
 */
class List_Pages_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return     string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List WordPress pages with optional filtering.';
	}

	/**
	 * Get instructions for the LLM on how to interpret output fields.
	 *
	 * @return string Instructions for the LLM.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'EXCERPT FIELDS: `has_excerpt` indicates if a manual excerpt is set. If true, `excerpt` contains the stored value. If false, `auto_excerpt` contains a truncated auto-generated excerpt from content (not stored - do not use for updates).';
	}

	/**
	 * Get the parameters 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(
				'parent'  => array(
					'type'        => 'integer',
					'description' => 'Parent page ID to filter by (0 for top-level pages)',
				),
				'author'  => array(
					'type'        => 'integer',
					'description' => 'Author ID to filter by',
				),
				'status'  => array(
					'type'        => 'string',
					'description' => 'Page status to filter by (publish, draft, etc.)',
					'enum'        => array( 'publish', 'draft', 'pending', 'private', 'future', 'trash', 'any' ),
				),
				'limit'   => array(
					'type'        => 'integer',
					'description' => 'Maximum number of pages to return',
					'default'     => 10,
				),
				'offset'  => array(
					'type'        => 'integer',
					'description' => 'Number of pages to skip',
					'default'     => 0,
				),
				'order'   => array(
					'type'        => 'string',
					'description' => 'Order of pages (ASC or DESC)',
					'enum'        => array( 'ASC', 'DESC' ),
					'default'     => 'ASC',
				),
				'orderby' => array(
					'type'        => 'string',
					'description' => 'Field to order pages by',
					'enum'        => array( 'date', 'title', 'modified', 'menu_order', 'rand' ),
					'default'     => 'menu_order',
				),
				'search'  => array(
					'type'        => 'string',
					'description' => 'Search term to find in pages',
				),
			),
			'required'   => array(),
		);
	}

	/**
	 * Check if the current user has permission to execute this tool.
	 *
	 * @return     bool Whether the user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'read' );
	}

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

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param      array $args The arguments for the tool.
	 * @return     array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		// Start building the query args
		$query_args = array(
			'post_type'      => 'page',
			'posts_per_page' => isset( $args['limit'] ) ? intval( $args['limit'] ) : 10,
			'offset'         => isset( $args['offset'] ) ? intval( $args['offset'] ) : 0,
			'order'          => $args['order'] ?? 'ASC',
			'orderby'        => $args['orderby'] ?? 'menu_order',
		);

		// Add parent filter if set
		if ( isset( $args['parent'] ) ) {
			$query_args['post_parent'] = intval( $args['parent'] );
		}

		if ( isset( $args['author'] ) && ! empty( $args['author'] ) ) {
			$query_args['author'] = intval( $args['author'] );
		}

		if ( isset( $args['status'] ) && ! empty( $args['status'] ) ) {
			if ( 'publish' !== $args['status'] && ! current_user_can( 'edit_pages' ) ) {
				return $this->error_response( 'You do not have permission to view pages with this status' );
			}
			$query_args['post_status'] = sanitize_text_field( $args['status'] );
		} elseif ( ! current_user_can( 'edit_pages' ) ) {
				$query_args['post_status'] = 'publish';
		}

		if ( isset( $args['search'] ) && ! empty( $args['search'] ) ) {
			$query_args['s'] = sanitize_text_field( $args['search'] );
		}

		// Get pages based on the query
		$pages_query = new \WP_Query( $query_args );
		$pages       = $pages_query->posts;

		// If no pages found
		if ( empty( $pages ) ) {
			return $this->success_response(
				'No pages found matching the criteria',
				array(
					'pages'    => array(),
					'count'    => 0,
					'total'    => 0,
					'limit'    => intval( $query_args['posts_per_page'] ),
					'offset'   => intval( $query_args['offset'] ),
					'has_more' => false,
				)
			);
		}

		// Format the pages data
		$formatted_pages = array();
		foreach ( $pages as $page ) {
			$has_excerpt = has_excerpt( $page );
			$page_data   = array(
				'id'          => $page->ID,
				'title'       => $page->post_title,
				'has_excerpt' => $has_excerpt,
				'date'        => $page->post_date,
				'modified'    => $page->post_modified,
				'status'      => $page->post_status,
				'slug'        => $page->post_name,
				'permalink'   => get_permalink( $page->ID ),
				'parent_id'   => $page->post_parent,
				'menu_order'  => $page->menu_order,
				'author'      => array(
					'id'   => $page->post_author,
					'name' => get_the_author_meta( 'display_name', $page->post_author ),
				),
			);

			if ( $has_excerpt ) {
				$page_data['excerpt'] = $page->post_excerpt;
			} else {
				$auto_excerpt = html_entity_decode( wp_strip_all_tags( get_the_excerpt( $page ) ), ENT_QUOTES, 'UTF-8' );
				if ( ! empty( $auto_excerpt ) ) {
					$page_data['auto_excerpt'] = String_Utils::truncate_to_token_boundary_with_ellipsis( $auto_excerpt, 200 );
				}
			}

			// Include featured image if exists
			if ( has_post_thumbnail( $page->ID ) ) {
				$page_data['featured_image'] = array(
					'id'  => get_post_thumbnail_id( $page->ID ),
					'url' => get_the_post_thumbnail_url( $page->ID, 'thumbnail' ),
				);
			}

			$formatted_pages[] = $page_data;
		}

		// Calculate pagination info
		$total_pages = $pages_query->found_posts;
		$offset      = $query_args['offset'];

		return $this->success_response(
			'Pages retrieved successfully',
			array(
				'pages'    => $formatted_pages,
				'count'    => count( $formatted_pages ),
				'total'    => $total_pages,
				'limit'    => $query_args['posts_per_page'],
				'offset'   => $offset,
				'has_more' => ( $offset + count( $formatted_pages ) ) < $total_pages,
			)
		);
	}
}
