<?php
/**
 * Download Media Tool.
 *
 * Downloads a file from a URL and adds it to the WordPress media library.
 * Uses download_url() and media_handle_sideload() for safe file handling.
 *
 * @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;
}

/**
 * Download_Media_Tool class.
 */
class Download_Media_Tool extends Tool {

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

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Download Media', '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 add it to the WordPress media library. Returns the attachment ID and URL.';
	}

	/**
	 * 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',
				),
				'title'   => array(
					'type'        => 'string',
					'description' => 'Title for the media item (default: filename)',
				),
				'post_id' => array(
					'type'        => 'integer',
					'description' => 'Post ID to attach the media to (default: 0, unattached)',
				),
			),
			'required'   => array( 'url' ),
		);
	}

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

	/**
	 * 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'] );
		$title   = $args['title'] ?? null;
		$post_id = $args['post_id'] ?? 0;

		if ( empty( $url ) ) {
			return $this->error_response( 'URL is required' );
		}

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

		require_once ABSPATH . 'wp-admin/includes/image.php';
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/media.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() );
		}

		$file_url_path = wp_parse_url( $url, PHP_URL_PATH );
		$file_info     = wp_check_filetype( basename( $file_url_path ) );
		$file          = array(
			'tmp_name' => $temp_file,
			'type'     => $file_info['type'],
			'name'     => basename( $file_url_path ),
			'size'     => filesize( $temp_file ),
		);

		$post_data     = $title ? array( 'post_title' => $title ) : array();
		$attachment_id = media_handle_sideload( $file, $post_id, $title, $post_data );

		// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.unlink_unlink -- temp file cleanup is best-effort; TODO: possibly migrate to WP_Filesystem later
		@unlink( $temp_file );

		if ( is_wp_error( $attachment_id ) ) {
			return $this->error_response( 'Failed to add to media library: ' . $attachment_id->get_error_message() );
		}

		$attachment = get_post( $attachment_id );

		return $this->success_response(
			'Media downloaded and added to library',
			array(
				'attachment_id' => $attachment_id,
				'url'           => wp_get_attachment_url( $attachment_id ),
				'title'         => $attachment->post_title,
				'file'          => get_attached_file( $attachment_id ),
				'mime_type'     => get_post_mime_type( $attachment_id ),
			)
		);
	}
}
