<?php
/**
 * List Post Types Tool.
 *
 * Allows the agent to list all registered post types in WordPress. Includes
 * built-in and custom post types with their capabilities and settings.
 *
 * @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_Post_Types_Tool class.
 */
class List_Post_Types_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List all registered post types in WordPress, including built-in and custom post types.';
	}

	/**
	 * 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(
				'public_only'  => array(
					'type'        => 'boolean',
					'description' => 'Whether to return only public post types',
					'default'     => false,
				),
				'show_ui'      => array(
					'type'        => 'boolean',
					'description' => 'Filter by whether the post type has a UI in the admin',
				),
				'hierarchical' => array(
					'type'        => 'boolean',
					'description' => 'Filter by whether the post type is hierarchical (like pages)',
				),
				'limit'        => array(
					'type'        => 'integer',
					'description' => 'Maximum number of post types to return. Default: 100.',
				),
				'offset'       => array(
					'type'        => 'integer',
					'description' => 'Number of post types to skip before returning results. Default: 0.',
				),
			),
			'required'   => array(),
		);
	}

	/**
	 * 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 ) {
		$query_args = array();

		if ( isset( $args['public_only'] ) && $args['public_only'] ) {
			$query_args['public'] = true;
		}

		if ( isset( $args['show_ui'] ) ) {
			$query_args['show_ui'] = (bool) $args['show_ui'];
		}

		if ( isset( $args['hierarchical'] ) ) {
			$query_args['hierarchical'] = (bool) $args['hierarchical'];
		}

		$post_types = get_post_types( $query_args, 'objects' );
		$limit      = max( 1, $args['limit'] ?? 100 );
		$offset     = max( 0, $args['offset'] ?? 0 );

		if ( empty( $post_types ) ) {
			return $this->success_response(
				'No post types found',
				array(
					'post_types' => array(),
					'count'      => 0,
					'total'      => 0,
					'limit'      => $limit,
					'offset'     => $offset,
					'has_more'   => false,
				)
			);
		}

		$formatted = array();
		foreach ( $post_types as $post_type ) {
			$count           = wp_count_posts( $post_type->name );
			$published_count = isset( $count->publish ) ? (int) $count->publish : 0;

			$formatted[] = array(
				'name'            => $post_type->name,
				'label'           => $post_type->label,
				'labels'          => array(
					'singular_name' => $post_type->labels->singular_name,
					'menu_name'     => $post_type->labels->menu_name,
				),
				'description'     => $post_type->description,
				'public'          => $post_type->public,
				'hierarchical'    => $post_type->hierarchical,
				'show_ui'         => $post_type->show_ui,
				'show_in_rest'    => $post_type->show_in_rest,
				'supports'        => get_all_post_type_supports( $post_type->name ),
				'taxonomies'      => get_object_taxonomies( $post_type->name ),
				'published_count' => $published_count,
				'builtin'         => $post_type->_builtin,
			);
		}

		// Sort by name
		usort(
			$formatted,
			function ( $a, $b ) {
				return strcmp( $a['name'], $b['name'] );
			}
		);

		// Apply pagination
		$total     = count( $formatted );
		$paginated = array_slice( $formatted, $offset, $limit );
		$has_more  = $total > ( $offset + $limit );

		return $this->success_response(
			'Post types retrieved successfully',
			array(
				'post_types' => $paginated,
				'count'      => count( $paginated ),
				'total'      => $total,
				'limit'      => $limit,
				'offset'     => $offset,
				'has_more'   => $has_more,
			)
		);
	}
}
