<?php
/**
 * Get Shortcode Details Tool.
 *
 * Returns detailed information about a shortcode including its callback function,
 * source file location, and source code when available.
 *
 * @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_Shortcode_Details_Tool class.
 */
class Get_Shortcode_Details_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Returns detailed information about a shortcode including its callback, source file, and source code: necessary to discover accepted shortcode parameters before rendering a shortcode.';
	}

	/**
	 * Get the parameters 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(
				'tag' => array(
					'type'        => 'string',
					'description' => 'The shortcode tag name (e.g., "gallery", "audio", "video").',
				),
			),
			'required'   => array( 'tag' ),
		);
	}

	/**
	 * Check if the current user has permission to execute this tool.
	 *
	 * @return bool Whether the user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool True - this 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 arguments for the tool.
	 * @return array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		global $shortcode_tags;

		$tag = $args['tag'];

		if ( ! shortcode_exists( $tag ) ) {
			return $this->error_response( String_Utils::replace_tags( 'Shortcode [{tag}] is not registered.', array( 'tag' => $tag ) ) );
		}

		$callback       = $shortcode_tags[ $tag ];
		$details        = $this->get_callback_details( $callback );
		$details['tag'] = $tag;

		return $this->success_response( 'Shortcode details retrieved', $details );
	}

	/**
	 * Get detailed callback information using reflection.
	 *
	 * @param mixed $callback The callback to analyze.
	 * @return array The callback details.
	 */
	private function get_callback_details( $callback ) {
		$details = array(
			'callback'    => PHP_Utils::get_callback_name( $callback ),
			'source_file' => null,
			'start_line'  => null,
			'end_line'    => null,
			'source_code' => null,
		);

		$reflection = PHP_Utils::get_callback_reflection( $callback );

		if ( $reflection ) {
			$file  = $reflection->getFileName();
			$start = $reflection->getStartLine();
			$end   = $reflection->getEndLine();

			if ( $file ) {
				$details['source_file'] = WordPress_Utils::get_relative_path( $file );
				$details['start_line']  = $start;
				$details['end_line']    = $end;
				$details['source_code'] = $this->extract_source_code( $file, $start, $end );
			}
		}

		return $details;
	}

	/**
	 * Extract source code from a file.
	 *
	 * @param string $file The file path.
	 * @param int    $start The starting line number (1-based).
	 * @param int    $end The ending line number (1-based, inclusive).
	 * @return string|null The source code, or null on failure.
	 */
	private function extract_source_code( $file, $start, $end ) {
		if ( ! is_readable( $file ) || $start < 1 || $end < $start ) {
			return null;
		}

		$lines = file( $file );
		if ( false === $lines ) {
			return null;
		}

		$extracted = array_slice( $lines, $start - 1, $end - $start + 1 );

		return implode( '', $extracted );
	}
}
