<?php
/**
 * Execute PHP Tool.
 *
 * Execute arbitrary PHP code for custom automation, debugging, and one-off tasks.
 * Uses eval() with full WordPress context 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;
}

/**
 * Execute_PHP_Tool class.
 */
class Execute_PHP_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Execute PHP code with full WordPress access (when the `calculate_php` tool is not sufficient).';
	}

	/**
	 * 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 for: calling WordPress functions, bulk data operations, debugging issues, custom automation tasks, database operations via `$wpdb`, interacting with the filesystem, sending emails, making HTTP requests, and any task requiring full PHP capabilities.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'PHP Version: ' . PHP_VERSION . PHP_EOL . <<<'INST'

EXECUTION CONTEXT:
- Code runs with FULL WordPress context (all functions, classes, globals available)
- Unrestricted PHP execution
- No <?php tags. Use "return", "echo", or "print" for output

AVAILABLE CAPABILITIES (in addition to built-in PHP functions):
- WordPress: All WP functions (get_posts, wp_insert_post, update_option, wp_remote_get, etc.)
- Database: \$wpdb global (query, get_results, insert, update, delete, prepare)
INST;
	}

	/**
	 * 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 false;
	}

	/**
	 * 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(
				'code' => array(
					'type'        => 'string',
					'description' => 'PHP code to execute. Do not include `<?php` tags. You MUST use `return`, `print`, or `echo` with the result value at the end of the script to get the output.',
				),
			),
			'required'   => array( 'code' ),
		);
	}

	/**
	 * Get the default enabled status for this tool.
	 *
	 * @return bool True if enabled by default, false otherwise.
	 * @since     1.0.0
	 */
	public function get_default_enabled_status() {
		return false;
	}

	/**
	 * 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 is_super_admin();
	}

	/**
	 * 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 ) {
		$code = $args['code'];

		ob_start();
		$error        = null;
		$return_value = null;

		try {
			// phpcs:ignore Generic.PHP.ForbiddenFunctions.Found, Squiz.PHP.Eval.Discouraged -- Intentional: eval() is the core functionality of this tool for executing LLM-provided PHP code for admin use only, disabled by default.
			$return_value = eval( $code );
		} catch ( \Throwable $e ) {
			$error = array(
				'type'    => get_class( $e ),
				'message' => $e->getMessage(),
				'file'    => $e->getFile(),
				'line'    => $e->getLine(),
			);
		}

		$output = ob_get_clean();

		if ( $error ) {
			return $this->error_response(
				'PHP execution failed: ' . $error['message'],
				array(
					'error'  => $error,
					'output' => $output,
				)
			);
		}

		$result = array(
			'output' => $output,
		);

		if ( null !== $return_value ) {
			$result['return_value'] = $return_value;
			$result['return_type']  = gettype( $return_value );
		}

		return $this->success_response( 'PHP code executed', $result );
	}
}
