<?php
/**
 * Delete File Tool.
 *
 * Delete a file or directory within the uploads or system temp directories.
 * Refuses to touch files that belong to the Media Library (use delete_media
 * for those) and never allows recursive deletion of a save-path root.
 *
 * @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://agenistrator.com/
 *
 * 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' ) ) {
	exit;
}

/**
 * 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 within the WordPress uploads directory or the system temporary directory.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'Use recursive=true to delete non-empty directories. Files that belong to the Media Library must be deleted with delete_media instead. The save-path roots themselves cannot be removed. Use this tool to clean up any temporary files you create under the system temp 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.
	 *
	 * Note: the path parameter description embeds the current value of
	 * WordPress_Utils::get_allowed_save_paths(). Its return value is typically
	 * stable, but a poorly behaved plugin filtering wp_upload_dir() dynamically
	 * could cause it to change between requests, invalidating LLM provider
	 * prompt caches and increasing API costs.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		$paths_desc = WordPress_Utils::format_paths_description( WordPress_Utils::get_allowed_save_paths() );
		return array(
			'type'       => 'object',
			'properties' => array(
				'path'      => array(
					'type'        => 'string',
					'description' => 'File or directory path (relative to WordPress root or absolute). Must be within one of: ' . $paths_desc . '. Use ' . DIRECTORY_SEPARATOR . ' as directory separator.',
				),
				'recursive' => array(
					'type'        => 'boolean',
					'description' => 'Delete directories recursively. Required for non-empty directories. Cannot be used on a save-path root. 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.
	 *
	 * Scoped to per-site save paths (wp_upload_dir() is per-site in multisite;
	 * manage_options is a per-site capability).
	 *
	 * @return bool True if the current user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * 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 = ! empty( $args['recursive'] );

		// 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'] );
		}

		// Restrict deletions to uploads and temp directories per plugin guidelines
		$validated_path = WordPress_Utils::is_allowed_save_path( $real_path );
		if ( false === $validated_path ) {
			return $this->error_response(
				'Invalid path: must be within one of: ' . WordPress_Utils::format_paths_description( WordPress_Utils::get_allowed_save_paths() )
			);
		}

		// Refuse to delete the save-path roots themselves (e.g. the uploads dir).
		foreach ( WordPress_Utils::get_allowed_save_paths() as $root ) {
			$real_root = realpath( $root );
			if ( false !== $real_root && $validated_path === $real_root ) {
				return $this->error_response( 'Refusing to delete save-path root: ' . $validated_path );
			}
		}

		// Media Library files must be deleted via delete_media so WordPress can
		// remove sub-sizes, post meta, and attachment data together. For a directory,
		// this also blocks recursive deletes that would strand any attachments inside.
		$is_dir         = is_dir( $validated_path );
		$attachment_ids = WordPress_Utils::get_attachment_ids_for_path( $validated_path );
		if ( ! empty( $attachment_ids ) ) {
			if ( $is_dir ) {
				return $this->error_response(
					'Files in this directory belong to Media Library attachments. Use delete_media to remove them first.',
					array( 'attachment_ids' => $attachment_ids )
				);
			}
			return $this->error_response(
				'This file belongs to a Media Library attachment. Use delete_media instead.',
				array( 'attachment_ids' => $attachment_ids )
			);
		}

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

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

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

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

	/**
	 * Delete a directory, optionally recursively.
	 *
	 * @param string $path      Absolute directory path.
	 * @param bool   $recursive Whether to recurse into subdirectories.
	 * @return bool True on success, false otherwise.
	 * @since     1.0.0
	 */
	private function delete_directory( $path, $recursive ) {
		if ( ! $recursive ) {
			$contents = array_diff( scandir( $path ), 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 );
	}

	/**
	 * Compute the recursive byte size of a directory.
	 *
	 * @param string $path Absolute directory path.
	 * @return int Total size in bytes.
	 * @since     1.0.0
	 */
	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;
	}
}
