<?php
/**
 * Update Post Tool.
 *
 * Allows the agent to update existing WordPress posts by ID or slug. Supports
 * partial updates for title, content, excerpt, categories, tags, and status.
 *
 * @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;
}

/**
 * Update_Post_Tool class.
 */
class Update_Post_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return     string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Update an existing WordPress post.';
	}

	/**
	 * Get usage instructions for the LLM.
	 *
	 * @return     string Instructions for using this tool.
	 * @since     1.0.0
	 */
	public function get_instructions() {
		return 'The `content` parameter MUST be valid HTML, NOT markdown. WordPress stores and renders post content as HTML. Use HTML tags like <p>, <h2>, <ul>, <li>, <a>, <strong>, <em>, etc.';
	}

	/**
	 * Get the parameters 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 post to update',
				),
				'title'              => array(
					'type'        => 'string',
					'description' => 'The new title of the post',
				),
				'content'            => array(
					'type'        => 'string',
					'description' => 'The new content of the post in HTML format (raw HTML, NOT markdown)',
				),
				'status'             => array(
					'type'        => 'string',
					'description' => 'The new status of the post',
					'enum'        => array( 'draft', 'publish', 'pending', 'private' ),
				),
				'categories'         => array(
					'type'        => 'array',
					'description' => 'Array of category IDs or names to assign to the post',
					'items'       => array(
						'type' => 'string',
					),
				),
				'tags'               => array(
					'type'        => 'array',
					'description' => 'Array of tag names to assign to the post',
					'items'       => array(
						'type' => 'string',
					),
				),
				'excerpt'            => array(
					'type'        => 'string',
					'description' => 'The excerpt/summary of the post in plain text format',
				),
				'featured_image_url' => array(
					'type'        => 'string',
					'description' => 'URL of an image to set as featured image',
				),
			),
			'required'   => array( 'id' ),
		);
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return     bool False - this tool modifies content.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Check if the current user has permission to execute this tool.
	 *
	 * @return     bool Whether the user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'edit_posts' );
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param      array $args The arguments for the tool.
	 * @return     array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		if ( ! isset( $args['id'] ) || empty( $args['id'] ) ) {
			return $this->error_response( 'Post ID is required' );
		}

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

		if ( ! $post ) {
			return $this->error_response( 'Post not found' );
		}

		// Check if post type is 'post'
		if ( 'post' !== $post->post_type ) {
			return $this->error_response( 'The specified ID is not a post' );
		}

		// Check if user can edit this post
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return $this->error_response( 'You do not have permission to edit this post' );
		}

		// Build update arguments
		$post_args = array(
			'ID' => $post_id,
		);

		// Update title if provided
		if ( isset( $args['title'] ) && ! empty( $args['title'] ) ) {
			$post_args['post_title'] = wp_strip_all_tags( $args['title'] );
		}

		// Update content if provided
		if ( isset( $args['content'] ) && ! empty( $args['content'] ) ) {
			$post_args['post_content'] = $args['content'];
		}

		// Update status if provided
		if ( isset( $args['status'] ) && ! empty( $args['status'] ) ) {
			$allowed_statuses = array( 'draft', 'publish', 'pending', 'private' );
			if ( ! in_array( $args['status'], $allowed_statuses, true ) ) {
				return $this->error_response( 'Invalid status. Must be one of: ' . implode( ', ', $allowed_statuses ) );
			}
			$post_args['post_status'] = $args['status'];
		}

		// Update excerpt if provided
		if ( isset( $args['excerpt'] ) && ! empty( $args['excerpt'] ) ) {
			$post_args['post_excerpt'] = wp_strip_all_tags( $args['excerpt'] );
		}

		// Update the post
		$updated = wp_update_post( $post_args );

		if ( is_wp_error( $updated ) ) {
			return $this->error_response( 'Failed to update post: ' . $updated->get_error_message() );
		}

		// Update categories if provided
		if ( isset( $args['categories'] ) && is_array( $args['categories'] ) && ! empty( $args['categories'] ) ) {
			$category_ids = array();

			foreach ( $args['categories'] as $category ) {
				if ( is_numeric( $category ) ) {
					$category_ids[] = (int) $category;
				} else {
					$term = term_exists( $category, 'category' );

					if ( ! $term ) {
						$term = wp_insert_term( $category, 'category' );
					}

					if ( is_array( $term ) && isset( $term['term_id'] ) ) {
						$category_ids[] = (int) $term['term_id'];
					}
				}
			}

			if ( ! empty( $category_ids ) ) {
				wp_set_post_categories( $post_id, $category_ids );
			}
		}

		// Update tags if provided
		if ( isset( $args['tags'] ) && is_array( $args['tags'] ) && ! empty( $args['tags'] ) ) {
			wp_set_post_tags( $post_id, $args['tags'] );
		}

		// Update featured image if URL provided
		if ( isset( $args['featured_image_url'] ) && ! empty( $args['featured_image_url'] ) ) {
			WordPress_Utils::set_featured_image_from_url( $post_id, $args['featured_image_url'] );
		}

		// Get updated post
		$updated_post = get_post( $post_id );

		return $this->success_response(
			'Post updated successfully',
			array(
				'post_id'     => $post_id,
				'post_title'  => $updated_post->post_title,
				'post_status' => $updated_post->post_status,
				'edit_link'   => get_edit_post_link( $post_id, 'raw' ),
				'view_link'   => get_permalink( $post_id ),
			)
		);
	}
}
