<?php
/**
 * Delete Plugin File Tool.
 *
 * Allows the agent to delete a file from a plugin directory. Validates path
 * within WP_PLUGIN_DIR and prevents main plugin file deletion.
 *
 * @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;
}

/**
 * Delete_Plugin_File_Tool class.
 */
class Delete_Plugin_File_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Delete a file from a plugin directory (cannot delete the main plugin file).';
	}

	/**
	 * 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(
				'plugin' => array(
					'type'        => 'string',
					'description' => 'Plugin slug (directory name) or main plugin file path',
				),
				'file'   => array(
					'type'        => 'string',
					'description' => 'Relative path to the file to delete within the plugin directory',
				),
			),
			'required'   => array( 'plugin', 'file' ),
		);
	}

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

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

	/**
	 * 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 ) {
		// Check if file modifications are disabled
		if ( ! wp_is_file_mod_allowed( 'capability_edit_plugins' ) ) {
			return $this->error_response( 'File modifications are disabled' );
		}

		// Check if file editing is disabled
		if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) {
			return $this->error_response( 'File editing is disabled (DISALLOW_FILE_EDIT is set)' );
		}

		if ( ! isset( $args['plugin'] ) || empty( trim( $args['plugin'] ) ) ) {
			return $this->error_response( 'Plugin identifier is required' );
		}
		if ( ! isset( $args['file'] ) || empty( trim( $args['file'] ) ) ) {
			return $this->error_response( 'File path is required' );
		}

		// Find the plugin using WordPress's plugin registry
		$plugin = WordPress_Utils::find_plugin( $args['plugin'] );
		if ( null === $plugin ) {
			return $this->error_response( 'Plugin not found: ' . $args['plugin'] );
		}

		$slug       = WordPress_Utils::get_plugin_slug( $plugin['file'] );
		$file       = $args['file'];
		$plugin_dir = WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $slug;
		$file_path  = $plugin_dir . DIRECTORY_SEPARATOR . $file;

		// Validate file path is within plugin directory
		$real_file_path  = realpath( $file_path );
		$real_plugin_dir = realpath( $plugin_dir );
		if ( false === $real_file_path || false === $real_plugin_dir ) {
			return $this->error_response( 'File does not exist' );
		}
		if ( ! PHP_Utils::is_path_within( $real_file_path, $real_plugin_dir ) ) {
			return $this->error_response( 'Invalid file path' );
		}

		// Prevent deletion of main plugin file (use actual main file from WordPress registry)
		$main_plugin_file = realpath( WP_PLUGIN_DIR . DIRECTORY_SEPARATOR . $plugin['file'] );
		if ( false !== $main_plugin_file && $main_plugin_file === $real_file_path ) {
			return $this->error_response( 'Cannot delete the main plugin file. Use uninstall_plugin to remove the entire plugin.' );
		}

		if ( ! is_file( $real_file_path ) ) {
			return $this->error_response( 'Path is not a file' );
		}

		// Delete the file
		// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- TODO: possibly migrate to WP_Filesystem later
		if ( ! unlink( $real_file_path ) ) {
			return $this->error_response( 'Failed to delete file' );
		}

		return $this->success_response(
			'File deleted successfully',
			array(
				'plugin' => $slug,
				'file'   => $file,
			)
		);
	}
}
