<?php
/**
 * Get Custom Post Tool.
 *
 * Allows the agent to retrieve detailed information about any post type by ID
 * or slug. Returns post content, metadata, taxonomies, and status information.
 *
 * @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_Custom_Post_Tool class.
 */
class Get_Custom_Post_Tool extends Tool {

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

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

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

	/**
	 * 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 `list_post_types` to see available post types.';
	}

	/**
	 * 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 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(
				'post_type'    => array(
					'type'        => 'string',
					'description' => 'The post type slug (e.g., "product", "event"). Required.',
				),
				'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 all post meta data',
					'default'     => true,
				),
			),
			'required'   => array( 'post_type' ),
		);
	}

	/**
	 * 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 current_user_can( 'read' );
	}

	/**
	 * 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 ( ! isset( $args['post_type'] ) || empty( $args['post_type'] ) ) {
			return $this->error_response( 'post_type is required' );
		}

		$post_type = sanitize_key( $args['post_type'] );

		if ( ! post_type_exists( $post_type ) ) {
			return $this->error_response( "Post type '{$post_type}' does not exist" );
		}

		$post_type_obj = get_post_type_object( $post_type );

		if ( ! current_user_can( $post_type_obj->cap->read ) ) {
			return $this->error_response( "You do not have permission to read {$post_type_obj->labels->name}" );
		}

		$post = null;

		// Get post by ID
		if ( isset( $args['id'] ) && is_numeric( $args['id'] ) ) {
			$post = get_post( $args['id'] );
			if ( $post && $post->post_type !== $post_type ) {
				return $this->error_response( "Post ID {$args['id']} is not of type '{$post_type}'" );
			}
		} elseif ( isset( $args['slug'] ) && ! empty( $args['slug'] ) ) {
			// Get post by slug
			$posts = get_posts(
				array(
					'name'           => sanitize_title( $args['slug'] ),
					'post_type'      => $post_type,
					'post_status'    => current_user_can( $post_type_obj->cap->edit_posts ) ? 'any' : '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' );
		}

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

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

		$has_excerpt = has_excerpt( $post );
		$post_data   = array(
			'id'              => $post->ID,
			'title'           => $post->post_title,
			'content'         => $post->post_content,
			'has_excerpt'     => $has_excerpt,
			'status'          => $post->post_status,
			'post_type'       => $post->post_type,
			'post_type_label' => $post_type_obj->labels->singular_name,
			'date'            => $post->post_date,
			'modified'        => $post->post_modified,
			'slug'            => $post->post_name,
			'permalink'       => get_permalink( $post->ID ),
			'menu_order'      => $post->menu_order,
			'parent'          => $post->post_parent,
			'author'          => array(
				'id'   => (int) $post->post_author,
				'name' => get_the_author_meta( 'display_name', $post->post_author ),
			),
		);

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

		// Include all taxonomies
		$post_data['taxonomies'] = array();
		$taxonomies              = get_object_taxonomies( $post_type, 'objects' );
		foreach ( $taxonomies as $tax ) {
			$terms = get_the_terms( $post->ID, $tax->name );
			if ( $terms && ! is_wp_error( $terms ) ) {
				$post_data['taxonomies'][ $tax->name ] = array(
					'label' => $tax->labels->name,
					'terms' => array_map(
						function ( $term ) {
							return array(
								'id'   => $term->term_id,
								'name' => $term->name,
								'slug' => $term->slug,
							);
						},
						$terms
					),
				);
			}
		}

		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_meta = ! isset( $args['include_meta'] ) || true === $args['include_meta'];
		if ( $include_meta ) {
			$post_data['meta'] = get_post_meta( $post->ID );
		}

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