<?php
/**
 * Get Media Details Tool.
 *
 * Allows the agent to retrieve detailed information about a specific media
 * item including metadata, dimensions, and registered image sizes.
 *
 * @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;
}

/**
 * Get_Media_Details_Tool class.
 */
class Get_Media_Details_Tool extends Tool {

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

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

	/**
	 * Get the tool description.
	 *
	 * @return string The tool description.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Get detailed information about a specific media item by ID.';
	}

	/**
	 * Get instructions for the LLM on how to interpret output fields.
	 *
	 * @return string Instructions for the LLM.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'CAPTION FIELDS: `has_caption` indicates if a manual caption is set. If true, `caption` contains the stored value. If false, `auto_caption` contains a truncated auto-generated caption from description (not stored - do not use for updates).';
	}

	/**
	 * 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(
				'id' => array(
					'type'        => 'integer',
					'description' => 'The ID of the media item to retrieve',
				),
			),
			'required'   => array( 'id' ),
		);
	}

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

	/**
	 * 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 ) {
		if ( ! isset( $args['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'Media ID is required' );
		}

		$attachment = get_post( intval( $args['id'] ) );

		if ( ! $attachment || 'attachment' !== $attachment->post_type ) {
			return $this->error_response( 'Media item not found' );
		}

		$metadata    = wp_get_attachment_metadata( $attachment->ID );
		$file_path   = get_attached_file( $attachment->ID );
		$has_caption = has_excerpt( $attachment );

		$media_data = array(
			'id'          => $attachment->ID,
			'title'       => $attachment->post_title,
			'has_caption' => $has_caption,
			'description' => $attachment->post_content,
			'alt'         => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
			'filename'    => basename( $file_path ),
			'url'         => wp_get_attachment_url( $attachment->ID ),
			'mime_type'   => $attachment->post_mime_type,
			'date'        => $attachment->post_date,
			'modified'    => $attachment->post_modified,
			'author'      => $attachment->post_author,
			'file_size'   => file_exists( $file_path ) ? filesize( $file_path ) : null,
		);

		if ( $has_caption ) {
			$media_data['caption'] = $attachment->post_excerpt;
		} else {
			$auto_caption = html_entity_decode( wp_strip_all_tags( get_the_excerpt( $attachment ) ), ENT_QUOTES, 'UTF-8' );
			if ( ! empty( $auto_caption ) ) {
				$media_data['auto_caption'] = String_Utils::truncate_to_token_boundary_with_ellipsis( $auto_caption, 1000 );
			}
		}

		if ( $metadata ) {
			if ( isset( $metadata['width'] ) ) {
				$media_data['width'] = $metadata['width'];
			}
			if ( isset( $metadata['height'] ) ) {
				$media_data['height'] = $metadata['height'];
			}
			if ( isset( $metadata['sizes'] ) ) {
				$media_data['sizes'] = array_keys( $metadata['sizes'] );
			}
		}

		// Get posts using this media as featured image
		// phpcs:disable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value -- Finding featured image usage requires meta lookup; limited to 10 posts, on-demand admin tool.
		$using_posts = get_posts(
			array(
				'meta_key'       => '_thumbnail_id',
				'meta_value'     => $attachment->ID,
				'post_type'      => 'any',
				'posts_per_page' => 10,
			)
		);
		// phpcs:enable WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.SlowDBQuery.slow_db_query_meta_value

		if ( ! empty( $using_posts ) ) {
			$media_data['used_as_featured_in'] = array();
			foreach ( $using_posts as $post ) {
				$media_data['used_as_featured_in'][] = array(
					'id'    => $post->ID,
					'title' => $post->post_title,
					'type'  => $post->post_type,
				);
			}
		}

		return $this->success_response(
			'Media item retrieved successfully',
			array(
				'media' => $media_data,
			)
		);
	}
}
