<?php
/**
 * Execute CLI Tool.
 *
 * Execute shell commands for system administration tasks. Uses proc_open
 * for process control with timeout handling and output capture.
 *
 * @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_CLI_Tool class.
 */
class Execute_CLI_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Execute a shell command. Useful for grep, find, rm, zip, tar, wp-cli, and other system commands.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'Commands run from the WordPress root directory.';
	}

	/**
	 * 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(
				'command' => array(
					'type'        => 'string',
					'description' => 'The shell command to execute.',
				),
				'cwd'     => array(
					'type'        => 'string',
					'description' => 'Working directory for the command. Default: WordPress root (ABSPATH).',
				),
				'timeout' => array(
					'type'        => 'integer',
					'description' => 'Timeout in seconds. Default: 30.',
				),
			),
			'required'   => array( 'command' ),
		);
	}

	/**
	 * 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 ) {
		$command = $args['command'];
		$cwd     = $args['cwd'] ?? ABSPATH;
		$timeout = $args['timeout'] ?? 30;

		if ( ! is_dir( $cwd ) ) {
			return $this->error_response( "Working directory does not exist: {$cwd}" );
		}

		// TODO: switch to using a shell wrapper library

		$descriptors = array(
			0 => array( 'pipe', 'r' ),
			1 => array( 'pipe', 'w' ),
			2 => array( 'pipe', 'w' ),
		);

		// phpcs:ignore Generic.PHP.ForbiddenFunctions.Found, WordPress.PHP.DiscouragedPHPFunctions.system_calls_proc_open -- Intentional: CLI execution tool for admin use only, disabled by default.
		$process = proc_open( $command, $descriptors, $pipes, $cwd );

		if ( ! is_resource( $process ) ) {
			return $this->error_response( 'Failed to execute command' );
		}

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- proc_open pipe handling
		fclose( $pipes[0] );

		stream_set_blocking( $pipes[1], false );
		stream_set_blocking( $pipes[2], false );

		$stdout     = '';
		$stderr     = '';
		$exit_code  = -1;
		$start_time = time();

		while ( true ) {
			$status = proc_get_status( $process );

			$stdout .= stream_get_contents( $pipes[1] );
			$stderr .= stream_get_contents( $pipes[2] );

			if ( ! $status['running'] ) {
				// Capture exit code from proc_get_status() - only the first call after
				// process exits returns the real value (proc_close() returns -1 after this)
				$exit_code = $status['exitcode'];
				break;
			}

			if ( ( time() - $start_time ) > $timeout ) {
				proc_terminate( $process, 9 );
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- proc_open pipe handling
				fclose( $pipes[1] );
				// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- proc_open pipe handling
				fclose( $pipes[2] );
				proc_close( $process );
				return $this->error_response(
					'Command timed out',
					array(
						'stdout'  => $stdout,
						'stderr'  => $stderr,
						'timeout' => $timeout,
					)
				);
			}

			usleep( 10000 );
		}

		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- proc_open pipe handling
		fclose( $pipes[1] );
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- proc_open pipe handling
		fclose( $pipes[2] );
		proc_close( $process );

		$result = array(
			'exit_code' => $exit_code,
			'stdout'    => $stdout,
			'stderr'    => $stderr,
			'cwd'       => $cwd,
		);

		if ( 0 !== $exit_code ) {
			return $this->error_response( "Command exited with code {$exit_code}", $result );
		}

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