<?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://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;

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

/**
 * 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 'For media library uploads, use the `download_media` tool instead.';
	}

	/**
	 * 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(
				'url'       => array(
					'type'        => 'string',
					'description' => 'The URL of the file to download',
				),
				'path'      => array(
					'type'        => 'string',
					'description' => 'Destination path relative to WordPress root (e.g., wp-content' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'file.txt) or absolute (e.g., ' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . 'file.txt for system temp directory). 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;
		}

		// Validate path is within allowed directories
		$full_path = WordPress_Utils::is_allowed_path( $full_path );
		if ( false === $full_path ) {
			return $this->error_response( 'Invalid path: must be within WordPress installation or system temp directory' );
		}

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

		// Move temp file to destination
		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.rename_rename -- silenced rename with proper fallback; TODO: possibly migrate to WP_Filesystem later
		if ( ! @rename( $temp_file, $full_path ) ) {
			// rename may fail across filesystems, try copy+delete
			// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- silenced copy with proper fallback
			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 );
		}

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