<?php
/**
 * Get Post Details Tool.
 *
 * Allows the agent to retrieve detailed information about WordPress posts by
 * ID or slug. Returns post content, metadata, categories, tags, 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_Post_Details_Tool class.
 */
class Get_Post_Details_Tool extends Tool {

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

	/**
	 * Get the tool name.
	 *
	 * @return     string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Get Post 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 post 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 post to retrieve',
				),
				'slug'             => array(
					'type'        => 'string',
					'description' => 'The slug (post_name) of the post to retrieve',
				),
				'include_meta'     => array(
					'type'        => 'boolean',
					'description' => 'Whether to include post 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 ) {
		$post = null;

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

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

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

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

		// 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(
			$post->post_content,
			$content_offset,
			$content_max_size
		);

		// Format the post data
		$has_excerpt = has_excerpt( $post );
		$post_data   = array(
			'id'                 => $post->ID,
			'title'              => $post->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'             => $post->post_status,
			'type'               => $post->post_type,
			'date'               => $post->post_date,
			'modified'           => $post->post_modified,
			'slug'               => $post->post_name,
			'permalink'          => get_permalink( $post->ID ),
			'author'             => array(
				'id'   => $post->post_author,
				'name' => get_the_author_meta( 'display_name', $post->post_author ),
			),
			'categories'         => array(),
			'tags'               => array(),
		);

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

		// Get categories
		$categories = get_the_category( $post->ID );
		if ( $categories ) {
			foreach ( $categories as $category ) {
				$post_data['categories'][] = array(
					'id'   => $category->term_id,
					'name' => $category->name,
					'slug' => $category->slug,
				);
			}
		}

		// Get tags
		$tags = get_the_tags( $post->ID );
		if ( $tags ) {
			foreach ( $tags as $tag ) {
				$post_data['tags'][] = array(
					'id'   => $tag->term_id,
					'name' => $tag->name,
					'slug' => $tag->slug,
				);
			}
		}

		// Include featured image if exists
		if ( has_post_thumbnail( $post->ID ) ) {
			$post_data['featured_image'] = array(
				'id'  => get_post_thumbnail_id( $post->ID ),
				'url' => get_the_post_thumbnail_url( $post->ID, 'full' ),
				'alt' => get_post_meta( get_post_thumbnail_id( $post->ID ), '_wp_attachment_image_alt', true ),
			);
		}

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

		return $this->success_response(
			'Post retrieved successfully',
			array(
				'post' => $post_data,
			)
		);
	}
}
