<?php
/**
 * List Tags Tool.
 *
 * Retrieve lists of WordPress post tags with filtering, search, and pagination.
 *
 * @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_Tags_Tool class.
 */
class List_Tags_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'List WordPress tags with optional filtering.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'TRUNCATION NOTE:
The `truncated_description` field is truncated for brevity. Use the `get_tag_details` tool with the tag ID to retrieve the full description.';
	}

	/**
	 * 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(
				'hide_empty' => array(
					'type'        => 'boolean',
					'description' => 'Whether to hide tags with no posts',
					'default'     => false,
				),
				'search'     => array(
					'type'        => 'string',
					'description' => 'Search term to find in tag names',
				),
				'limit'      => array(
					'type'        => 'integer',
					'description' => 'Maximum number of tags to return',
					'default'     => 100,
				),
				'offset'     => array(
					'type'        => 'integer',
					'description' => 'Number of tags to skip',
					'default'     => 0,
				),
				'orderby'    => array(
					'type'        => 'string',
					'description' => 'Field to order by',
					'enum'        => array( 'name', 'slug', 'term_id', 'count' ),
					'default'     => 'name',
				),
				'order'      => array(
					'type'        => 'string',
					'description' => 'Order direction',
					'enum'        => array( 'ASC', 'DESC' ),
					'default'     => 'ASC',
				),
			),
			'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(
			'taxonomy'   => 'post_tag',
			'number'     => isset( $args['limit'] ) ? intval( $args['limit'] ) : 100,
			'offset'     => isset( $args['offset'] ) ? intval( $args['offset'] ) : 0,
			'orderby'    => $args['orderby'] ?? 'name',
			'order'      => $args['order'] ?? 'ASC',
			'hide_empty' => $args['hide_empty'] ?? false,
		);

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

		$tags = get_terms( $query_args );

		if ( is_wp_error( $tags ) ) {
			return $this->error_response( 'Failed to retrieve tags: ' . $tags->get_error_message() );
		}

		$limit  = intval( $query_args['number'] );
		$offset = intval( $query_args['offset'] );

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

		// Get true total count with same filters but no limit/offset
		$count_args = array_merge(
			$query_args,
			array(
				'number' => 0,
				'offset' => 0,
				'fields' => 'count',
			)
		);
		$total      = (int) get_terms( $count_args );

		$formatted = array();
		foreach ( $tags as $tag ) {
			$formatted[] = array(
				'id'                    => $tag->term_id,
				'name'                  => $tag->name,
				'slug'                  => $tag->slug,
				'truncated_description' => String_Utils::truncate_to_token_boundary_with_ellipsis( $tag->description, 200 ),
				'count'                 => $tag->count,
			);
		}

		return $this->success_response(
			'Tags retrieved successfully',
			array(
				'tags'     => $formatted,
				'count'    => count( $formatted ),
				'total'    => $total,
				'limit'    => $limit,
				'offset'   => $offset,
				'has_more' => ( $offset + count( $formatted ) ) < $total,
			)
		);
	}
}
