<?php
/**
 * Delete File Tool.
 *
 * Delete a file or directory with recursive support and path validation
 * to prevent deletion outside allowed paths.
 *
 * @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_File_Tool class.
 */
class Delete_File_Tool extends Tool {

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

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

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

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'Paths are relative to WordPress root unless absolute. Use recursive=true to delete non-empty directories.';
	}

	/**
	 * 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(
				'path'      => array(
					'type'        => 'string',
					'description' => 'File or directory path (relative to WordPress root or absolute). Use ' . DIRECTORY_SEPARATOR . ' as directory separator.',
				),
				'recursive' => array(
					'type'        => 'boolean',
					'description' => 'Delete directories recursively. Required for non-empty directories. Default: false.',
				),
			),
			'required'   => array( 'path' ),
		);
	}

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

		$path      = $args['path'];
		$recursive = $args['recursive'] ?? false;

		// Convert relative paths to absolute
		if ( strncmp( $path, DIRECTORY_SEPARATOR, strlen( DIRECTORY_SEPARATOR ) ) !== 0 ) {
			$path = ABSPATH . $path;
		}

		// File/directory must exist for deletion
		$real_path = realpath( $path );
		if ( false === $real_path || ! file_exists( $real_path ) ) {
			return $this->error_response( 'File not found: ' . $args['path'] );
		}

		// Validate path is within allowed directories (ABSPATH, WP_CONTENT_DIR, or temp dir)
		// This also prevents deletion of root directories themselves (they don't match prefix + separator)
		$validated_path = WordPress_Utils::is_allowed_path( $real_path );
		if ( false === $validated_path ) {
			return $this->error_response( 'Invalid path: must be within WordPress installation or system temp directory' );
		}

		$path = $validated_path;

		$is_dir = is_dir( $path );
		$size   = $is_dir ? $this->get_directory_size( $path ) : filesize( $path );

		if ( $is_dir ) {
			$result = $this->delete_directory( $path, $recursive );
		} else {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- TODO: possibly migrate to WP_Filesystem later
			$result = unlink( $path );
		}

		if ( ! $result ) {
			return $this->error_response( 'Failed to delete: ' . $args['path'] );
		}

		return $this->success_response(
			'Deleted successfully',
			array(
				'path'         => $path,
				'type'         => $is_dir ? 'directory' : 'file',
				'size_deleted' => $size,
			)
		);
	}

	private function delete_directory( $path, $recursive ) {
		if ( ! $recursive ) {
			$contents = scandir( $path );
			$contents = array_diff( $contents, array( '.', '..' ) );
			if ( ! empty( $contents ) ) {
				return false;
			}
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- TODO: possibly migrate to WP_Filesystem later
			return rmdir( $path );
		}

		$files = array_diff( scandir( $path ), array( '.', '..' ) );
		foreach ( $files as $file ) {
			$full_path = $path . DIRECTORY_SEPARATOR . $file;
			if ( is_dir( $full_path ) ) {
				$this->delete_directory( $full_path, true );
			} else {
				// phpcs:ignore WordPress.WP.AlternativeFunctions.unlink_unlink -- TODO: possibly migrate to WP_Filesystem later
				unlink( $full_path );
			}
		}
		// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_rmdir -- TODO: possibly migrate to WP_Filesystem later
		return rmdir( $path );
	}

	private function get_directory_size( $path ) {
		$size  = 0;
		$files = new \RecursiveIteratorIterator(
			new \RecursiveDirectoryIterator( $path, \RecursiveDirectoryIterator::SKIP_DOTS )
		);
		foreach ( $files as $file ) {
			$size += $file->getSize();
		}
		return $size;
	}
}
