<?php
/**
 * Download File Tool.
 *
 * Download a file from a URL and save it to a specified path on the server.
 * Uses wp_remote_get() for the request and validates destination path.
 *
 * @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;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Download_File_Tool class.
 */
class Download_File_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Download a file from a URL and save it to a specified path on the server.';
	}

	/**
	 * Get additional description instructions for the LLM.
	 *
	 * @return string Additional instructions appended to description.
	 * @since     1.0.0
	 */
	public function get_description_instructions() {
		return 'To add a remote file to the media library, download it here first, then call `create_media` with the resulting path. When you download temporarily for an intermediate step, delete the file with `delete_file` once it is no longer needed.';
	}

	/**
	 * Get the parameters schema for this tool.
	 *
	 * Note: the 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() {
		$save_paths_desc = WordPress_Utils::format_paths_description( WordPress_Utils::get_allowed_save_paths() );
		return array(
			'type'       => 'object',
			'properties' => array(
				'url'       => array(
					'type'        => 'string',
					'description' => 'The URL of the file to download',
				),
				'path'      => array(
					'type'        => 'string',
					'description' => 'Destination file path (relative to WordPress root or absolute). Must be within one of: ' . $save_paths_desc . '. Use ' . DIRECTORY_SEPARATOR . ' as directory separator.',
				),
				'overwrite' => array(
					'type'        => 'boolean',
					'description' => 'Overwrite existing file if it exists (default: false)',
				),
			),
			'required'   => array( 'url', '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 current_user_can( 'manage_options' );
	}

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

	/**
	 * 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 ) {
		$url       = esc_url_raw( $args['url'] );
		$path      = $args['path'];
		$overwrite = $args['overwrite'] ?? false;

		if ( empty( $url ) || empty( $path ) ) {
			return $this->error_response( 'URL and path are required' );
		}

		if ( ! wp_http_validate_url( $url ) ) {
			return $this->error_response( 'Invalid URL' );
		}

		// Resolve path (support both relative and absolute paths)
		if ( strncmp( $path, DIRECTORY_SEPARATOR, strlen( DIRECTORY_SEPARATOR ) ) !== 0 ) {
			$full_path = ABSPATH . $path;
		} else {
			$full_path = $path;
		}

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

		// Create directory if needed
		$dir = dirname( $full_path );
		if ( ! is_dir( $dir ) && ! wp_mkdir_p( $dir ) ) {
			return $this->error_response( 'Failed to create directory: ' . $dir );
		}

		// Check if file exists and overwrite is disabled
		if ( file_exists( $full_path ) && ! $overwrite ) {
			return $this->error_response( 'File already exists. Set overwrite=true to replace it.' );
		}

		require_once ABSPATH . 'wp-admin/includes/file.php';

		$set_user_agent = function ( $args ) {
			$args['user-agent'] = 'Agenistrator/' . AGENISTRATOR_VERSION;
			return $args;
		};
		add_filter( 'http_request_args', $set_user_agent, 10, 1 );
		$temp_file = download_url( $url );
		remove_filter( 'http_request_args', $set_user_agent, 10 );

		if ( is_wp_error( $temp_file ) ) {
			return $this->error_response( 'Download failed: ' . $temp_file->get_error_message() );
		}

		// MIME validation for files going into the uploads directory (mirrors core's sideload behavior)
		if ( WordPress_Utils::is_in_uploads( $full_path ) ) {
			$filetype = wp_check_filetype_and_ext( $temp_file, basename( $full_path ) );
			if ( ( empty( $filetype['ext'] ) || empty( $filetype['type'] ) ) && ! current_user_can( 'unfiltered_upload' ) ) {
				// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- best-effort cleanup; TODO: possibly migrate to WP_Filesystem later
				@unlink( $temp_file );
				return $this->error_response( 'File type not allowed for uploads directory' );
			}
		}

		// Move to destination using copy+unlink (stream-safe; matches core sideload behavior)
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- silenced copy with proper fallback; TODO: possibly migrate to WP_Filesystem later
		if ( ! @copy( $temp_file, $full_path ) ) {
			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- best-effort cleanup; TODO: possibly migrate to WP_Filesystem later
			@unlink( $temp_file );
			return $this->error_response( 'Failed to save file to: ' . $path );
		}
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- best-effort cleanup; TODO: possibly migrate to WP_Filesystem later
		@unlink( $temp_file );

		// Set permissions derived from parent directory (matches core behavior)
		$stat = stat( $dir );
		if ( false !== $stat ) {
			// phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- matches core _wp_handle_upload() behavior
			chmod( $full_path, $stat['mode'] & 0000666 );
		}

		return $this->success_response(
			'File downloaded successfully',
			array(
				'full_path' => $full_path,
				'size'      => filesize( $full_path ),
				'mime_type' => wp_check_filetype( $full_path )['type'] ?? 'unknown',
			)
		);
	}
}
