<?php
/**
 * List Taxonomies Tool.
 *
 * List all registered taxonomies with filtering by public/private status
 * and associated post types. Uses get_taxonomies().
 *
 * @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_Taxonomies_Tool class.
 */
class List_Taxonomies_Tool extends Tool {

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

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

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

	/**
	 * 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 taxonomies',
					'default'     => false,
				),
				'object_type' => array(
					'type'        => 'string',
					'description' => 'Filter taxonomies by the object type they are registered for (e.g., "post", "page")',
				),
				'show_ui'     => array(
					'type'        => 'boolean',
					'description' => 'Filter by whether the taxonomy has a UI in the admin',
				),
				'limit'       => array(
					'type'        => 'integer',
					'description' => 'Maximum number of taxonomies to return. Default: 100.',
				),
				'offset'      => array(
					'type'        => 'integer',
					'description' => 'Number of taxonomies 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'];
		}

		$taxonomies = get_taxonomies( $query_args, 'objects' );

		// Filter by object type if specified
		if ( isset( $args['object_type'] ) && ! empty( $args['object_type'] ) ) {
			$object_type = sanitize_text_field( $args['object_type'] );
			$taxonomies  = array_filter(
				$taxonomies,
				function ( $taxonomy ) use ( $object_type ) {
					return in_array( $object_type, $taxonomy->object_type, true );
				}
			);
		}

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

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

		$formatted = array();
		foreach ( $taxonomies as $taxonomy ) {
			$term_count = wp_count_terms(
				array(
					'taxonomy'   => $taxonomy->name,
					'hide_empty' => false,
				)
			);

			$formatted[] = array(
				'name'         => $taxonomy->name,
				'label'        => $taxonomy->label,
				'labels'       => array(
					'singular_name' => $taxonomy->labels->singular_name,
					'menu_name'     => $taxonomy->labels->menu_name,
				),
				'description'  => $taxonomy->description,
				'public'       => $taxonomy->public,
				'hierarchical' => $taxonomy->hierarchical,
				'show_ui'      => $taxonomy->show_ui,
				'show_in_rest' => $taxonomy->show_in_rest,
				'object_types' => $taxonomy->object_type,
				'term_count'   => is_wp_error( $term_count ) ? 0 : (int) $term_count,
				'builtin'      => $taxonomy->_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(
			'Taxonomies retrieved successfully',
			array(
				'taxonomies' => $paginated,
				'count'      => count( $paginated ),
				'total'      => $total,
				'limit'      => $limit,
				'offset'     => $offset,
				'has_more'   => $has_more,
			)
		);
	}
}
