<?php
/**
 * Get Page Details Tool.
 *
 * Allows the agent to retrieve detailed information about WordPress pages by
 * ID or slug. Returns page content, metadata, and status information in a
 * structured format.
 *
 * @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://maximum.software/
 *
 * 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' ) ) {
	return;
}

/**
 * Get_Page_Details_Tool class.
 */
class Get_Page_Details_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return     string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Get detailed information about a specific WordPress page by ID or slug.';
	}

	/**
	 * 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(
				'id'               => array(
					'type'        => 'integer',
					'description' => 'The ID of the page to retrieve',
				),
				'slug'             => array(
					'type'        => 'string',
					'description' => 'The slug of the page to retrieve',
				),
				'include_meta'     => array(
					'type'        => 'boolean',
					'description' => 'Whether to include page meta data',
					'default'     => false,
				),
				'content_offset'   => array(
					'type'        => 'integer',
					'description' => 'Byte offset for content chunking (use 0 for first chunk, then use content_offset + content_size from response for next chunk)',
					'default'     => 0,
				),
				'content_max_size' => array(
					'type'        => 'integer',
					'description' => 'Maximum size of content chunk in bytes',
					'default'     => 8192,
				),
			),
			'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 ) {
		$page = null;

		// Get page by ID
		if ( isset( $args['id'] ) && is_numeric( $args['id'] ) ) {
			$page = get_post( $args['id'] );
		} elseif ( isset( $args['slug'] ) && ! empty( $args['slug'] ) ) {
			// Get page by slug
			$pages = get_posts(
				array(
					'name'           => $args['slug'],
					'post_type'      => 'page',
					'post_status'    => 'publish',
					'posts_per_page' => 1,
				)
			);

			if ( ! empty( $pages ) ) {
				$page = $pages[0];
			}
		} else {
			// No identifier provided
			return $this->error_response( 'Either page ID or slug is required' );
		}

		// Check if page exists
		if ( ! $page ) {
			return $this->error_response( 'Page not found' );
		}

		// Check if post type is page
		if ( 'page' !== $page->post_type ) {
			return $this->error_response( 'The specified ID or slug is not a page' );
		}

		// Check if user has permission to read this page
		if ( ! current_user_can( 'read_page', $page->ID ) ) {
			return $this->error_response( 'You do not have permission to view this page' );
		}

		// Get chunking parameters
		$content_offset   = isset( $args['content_offset'] ) ? intval( $args['content_offset'] ) : 0;
		$content_max_size = isset( $args['content_max_size'] ) ? intval( $args['content_max_size'] ) : 8192;

		// Chunk the content using token-boundary splitting
		$content_chunk = String_Utils::split_on_token_boundary(
			$page->post_content,
			$content_offset,
			$content_max_size
		);

		// Format the page data
		$has_excerpt = has_excerpt( $page );
		$page_data   = array(
			'id'                 => $page->ID,
			'title'              => $page->post_title,
			'content'            => $content_chunk['content'],
			'content_total_size' => $content_chunk['total_size'],
			'content_offset'     => $content_chunk['offset'],
			'content_size'       => $content_chunk['size'],
			'content_has_more'   => $content_chunk['has_more'],
			'has_excerpt'        => $has_excerpt,
			'status'             => $page->post_status,
			'date'               => $page->post_date,
			'modified'           => $page->post_modified,
			'slug'               => $page->post_name,
			'permalink'          => get_permalink( $page->ID ),
			'author'             => array(
				'id'   => $page->post_author,
				'name' => get_the_author_meta( 'display_name', $page->post_author ),
			),
			'template'           => get_page_template_slug( $page->ID ),
		);

		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, 1000 );
			}
		}

		// Add parent page information if it exists
		if ( $page->post_parent > 0 ) {
			$parent = get_post( $page->post_parent );
			if ( $parent ) {
				$page_data['parent'] = array(
					'id'    => $parent->ID,
					'title' => $parent->post_title,
					'slug'  => $parent->post_name,
				);
			}
		}

		// Include child pages if they exist
		$children = get_pages(
			array(
				'child_of'    => $page->ID,
				'sort_column' => 'menu_order,post_title',
			)
		);

		if ( ! empty( $children ) ) {
			$page_data['children'] = array();
			foreach ( $children as $child ) {
				$page_data['children'][] = array(
					'id'    => $child->ID,
					'title' => $child->post_title,
					'slug'  => $child->post_name,
				);
			}
		}

		// 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, 'full' ),
				'alt' => get_post_meta( get_post_thumbnail_id( $page->ID ), '_wp_attachment_image_alt', true ),
			);
		}

		// Include metadata if requested
		if ( isset( $args['include_meta'] ) && true === $args['include_meta'] ) {
			$page_data['meta'] = get_post_meta( $page->ID );
		}

		return $this->success_response(
			'Page retrieved successfully',
			array(
				'page' => $page_data,
			)
		);
	}
}
