<?php
/**
 * Create Post Tool.
 *
 * Allows the agent to create new WordPress posts with specified content, title,
 * categories, tags, and other post attributes. Handles validation and error
 * reporting.
 *
 * @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;
}

/**
 * Create_Post_Tool class.
 */
class Create_Post_Tool extends Tool {

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

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

	/**
	 * Get the description of the tool.
	 *
	 * @return     string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Create a new 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(
				'title'              => array(
					'type'        => 'string',
					'description' => 'The title of the post',
				),
				'content'            => array(
					'type'        => 'string',
					'description' => 'The content of the post in HTML format (raw HTML, NOT markdown)',
				),
				'status'             => array(
					'type'        => 'string',
					'description' => 'The status of the post',
					'enum'        => array( 'draft', 'publish', 'pending', 'private' ),
				),
				'categories'         => array(
					'type'        => 'array',
					'description' => 'Array of category IDs or names',
					'items'       => array(
						'type' => 'string',
					),
				),
				'tags'               => array(
					'type'        => 'array',
					'description' => 'Array of tag names',
					'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( 'title', 'content' ),
		);
	}

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

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

	/**
	 * 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['title'] ) || empty( $args['title'] ) ) {
			return $this->error_response( 'Title is required' );
		}

		if ( ! isset( $args['content'] ) || empty( $args['content'] ) ) {
			return $this->error_response( 'Content is required' );
		}

		$status           = $args['status'] ?? 'draft';
		$allowed_statuses = array( 'draft', 'publish', 'pending', 'private' );

		if ( ! in_array( $status, $allowed_statuses, true ) ) {
			return $this->error_response( 'Invalid status. Must be one of: ' . implode( ', ', $allowed_statuses ) );
		}

		$post_args = array(
			'post_title'   => wp_strip_all_tags( $args['title'] ),
			'post_content' => $args['content'],
			'post_status'  => $status,
			'post_type'    => 'post',
			'post_author'  => get_current_user_id(),
		);

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

		// Insert the post
		$post_id = wp_insert_post( $post_args );

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

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

			foreach ( $args['categories'] as $category ) {
				if ( is_numeric( $category ) ) {
					// If it's an ID, use it directly
					$category_ids[] = (int) $category;
				} else {
					// If it's a name/slug, try to find it or create it
					$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 );
			}
		}

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

		// Handle 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'] );
		}

		return $this->success_response(
			'Post created successfully',
			array(
				'post_id'     => $post_id,
				'post_title'  => $args['title'],
				'post_status' => $status,
				'edit_link'   => get_edit_post_link( $post_id, 'raw' ),
				'view_link'   => get_permalink( $post_id ),
			)
		);
	}
}
