<?php
/**
 * List Custom Posts Tool.
 *
 * Allows the agent to retrieve lists of posts from any post type with filtering
 * options including status, pagination, ordering, and taxonomy queries.
 *
 * @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;
}

/**
 * List_Custom_Posts_Tool class.
 */
class List_Custom_Posts_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List posts of any post type (custom or built-in) with filtering.';
	}

	/**
	 * 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", "book"). Required.',
				),
				'taxonomy_query'  => array(
					'type'                 => 'object',
					'description'          => 'Filter by taxonomy terms. Keys are taxonomy slugs, values are term IDs or slugs.',
					'additionalProperties' => array(
						'oneOf' => array(
							array( 'type' => 'string' ),
							array( 'type' => 'integer' ),
							array(
								'type'  => 'array',
								'items' => array( 'oneOf' => array( array( 'type' => 'string' ), array( 'type' => 'integer' ) ) ),
							),
						),
					),
				),
				'author'          => array(
					'type'        => 'integer',
					'description' => 'Author ID to filter by',
				),
				'status'          => array(
					'type'        => 'string',
					'description' => 'Post status to filter by',
					'enum'        => array( 'publish', 'draft', 'pending', 'private', 'future', 'trash', 'any' ),
				),
				'limit'           => array(
					'type'        => 'integer',
					'description' => 'Maximum number of posts to return (default: 10, max: 100)',
					'default'     => 10,
				),
				'offset'          => array(
					'type'        => 'integer',
					'description' => 'Number of posts to skip',
					'default'     => 0,
				),
				'order'           => array(
					'type'        => 'string',
					'description' => 'Order of posts (ASC or DESC)',
					'enum'        => array( 'ASC', 'DESC' ),
					'default'     => 'DESC',
				),
				'orderby'         => array(
					'type'        => 'string',
					'description' => 'Field to order posts by',
					'enum'        => array( 'date', 'title', 'modified', 'menu_order', 'rand', 'ID' ),
					'default'     => 'date',
				),
				'search'          => array(
					'type'        => 'string',
					'description' => 'Search term to find in posts',
				),
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Tool parameter definition; actual queries are limited in scope and run on-demand by admin users.
				'meta_query'      => array(
					'type'        => 'array',
					'description' => 'Meta query for filtering by custom fields',
					'items'       => array(
						'type'       => 'object',
						'properties' => array(
							'key'     => array( 'type' => 'string' ),
							'value'   => array(
								'oneOf' => array(
									array( 'type' => 'string' ),
									array( 'type' => 'number' ),
									array(
										'type'  => 'array',
										'items' => array(),
									),
								),
							),
							'compare' => array(
								'type' => 'string',
								'enum' => array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'EXISTS', 'NOT EXISTS' ),
							),
							'type'    => array(
								'type' => 'string',
								'enum' => array( 'NUMERIC', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'UNSIGNED' ),
							),
						),
					),
				),
				'include_content' => array(
					'type'        => 'boolean',
					'description' => 'Include full post content in response',
					'default'     => false,
				),
				'include_meta'    => array(
					'type'        => 'boolean',
					'description' => 'Include all post meta in response',
					'default'     => false,
				),
			),
			'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 );

		// Check read capability for this 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}" );
		}

		$limit = isset( $args['limit'] ) ? min( 100, max( 1, intval( $args['limit'] ) ) ) : 10;

		$query_args = array(
			'post_type'      => $post_type,
			'posts_per_page' => $limit,
			'offset'         => isset( $args['offset'] ) ? max( 0, intval( $args['offset'] ) ) : 0,
			'order'          => isset( $args['order'] ) && in_array( $args['order'], array( 'ASC', 'DESC' ), true ) ? $args['order'] : 'DESC',
			'orderby'        => $args['orderby'] ?? 'date',
		);

		// Handle status with capability check
		if ( isset( $args['status'] ) && ! empty( $args['status'] ) ) {
			if ( 'publish' !== $args['status'] && ! current_user_can( $post_type_obj->cap->edit_posts ) ) {
				return $this->error_response( 'You do not have permission to view posts with this status' );
			}
			$query_args['post_status'] = $args['status'];
		} else {
			$query_args['post_status'] = current_user_can( $post_type_obj->cap->edit_posts ) ? 'any' : 'publish';
		}

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

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

		// Build taxonomy query
		if ( isset( $args['taxonomy_query'] ) && is_array( $args['taxonomy_query'] ) && ! empty( $args['taxonomy_query'] ) ) {
			$tax_query        = array();
			$valid_taxonomies = get_object_taxonomies( $post_type );

			foreach ( $args['taxonomy_query'] as $taxonomy => $terms ) {
				$taxonomy = sanitize_key( $taxonomy );
				if ( ! in_array( $taxonomy, $valid_taxonomies, true ) ) {
					return $this->error_response( "Taxonomy '{$taxonomy}' is not registered for post type '{$post_type}'" );
				}

				$term_values = is_array( $terms ) ? $terms : array( $terms );
				$field       = is_numeric( $term_values[0] ) ? 'term_id' : 'slug';

				$tax_query[] = array(
					'taxonomy' => $taxonomy,
					'field'    => $field,
					'terms'    => $term_values,
				);
			}

			if ( ! empty( $tax_query ) ) {
				// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query -- Standard WordPress taxonomy query; limited scope, on-demand admin tool.
				$query_args['tax_query'] = $tax_query;
			}
		}

		// Build meta query
		if ( isset( $args['meta_query'] ) && is_array( $args['meta_query'] ) && ! empty( $args['meta_query'] ) ) {
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Standard WordPress meta query; limited scope, on-demand admin tool.
			$query_args['meta_query'] = array_map(
				function ( $meta ) {
					return array(
						'key'     => sanitize_key( $meta['key'] ?? '' ),
						'value'   => $meta['value'] ?? '',
						'compare' => $meta['compare'] ?? '=',
						'type'    => $meta['type'] ?? 'CHAR',
					);
				},
				$args['meta_query']
			);
		}

		$posts_query = new \WP_Query( $query_args );

		if ( empty( $posts_query->posts ) ) {
			return $this->success_response(
				'No posts found',
				array(
					'posts'    => array(),
					'count'    => 0,
					'total'    => 0,
					'limit'    => intval( $query_args['posts_per_page'] ),
					'offset'   => intval( $query_args['offset'] ),
					'has_more' => false,
				)
			);
		}

		$formatted_posts = array();
		$include_content = isset( $args['include_content'] ) && true === $args['include_content'];
		$include_meta    = isset( $args['include_meta'] ) && true === $args['include_meta'];

		foreach ( $posts_query->posts as $post ) {
			$has_excerpt = has_excerpt( $post );
			$post_data   = array(
				'id'          => $post->ID,
				'title'       => $post->post_title,
				'has_excerpt' => $has_excerpt,
				'date'        => $post->post_date,
				'modified'    => $post->post_modified,
				'status'      => $post->post_status,
				'slug'        => $post->post_name,
				'permalink'   => get_permalink( $post->ID ),
				'author'      => array(
					'id'   => (int) $post->post_author,
					'name' => get_the_author_meta( 'display_name', $post->post_author ),
				),
				'menu_order'  => $post->menu_order,
			);

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

			if ( $include_content ) {
				$post_data['content'] = $post->post_content;
			}

			// Include 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_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, 'thumbnail' ),
				);
			}

			if ( $include_meta ) {
				$post_data['meta'] = get_post_meta( $post->ID );
			}

			$formatted_posts[] = $post_data;
		}

		$offset = $query_args['offset'];

		return $this->success_response(
			'Posts retrieved successfully',
			array(
				'post_type'       => $post_type,
				'post_type_label' => $post_type_obj->labels->name,
				'posts'           => $formatted_posts,
				'count'           => count( $formatted_posts ),
				'total'           => $posts_query->found_posts,
				'limit'           => $limit,
				'offset'          => $offset,
				'has_more'        => ( $offset + count( $formatted_posts ) ) < $posts_query->found_posts,
			)
		);
	}
}
