<?php
/**
 * Tool for saving meta descriptions to WordPress posts.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

defined( 'ABSPATH' ) || exit;

/**
 * Tool for saving meta descriptions to WordPress posts.
 * Saves meta descriptions to custom meta fields and validates permissions.
 */
class Tool_Save_Meta_Description {

	/**
	 * Define tool schema for OpenAI Responses API.
	 *
	 * @return array Schema definition
	 */
	public static function schema(): array {
		return array(
			'type'        => 'function',
			'name'        => 'save_meta_description',
			'description' => 'Save generated meta description to WordPress post',
			'strict'      => true,
			'parameters'  => array(
				'type'                 => 'object',
				'properties'           => array(
					'post_id'          => array(
						'type'        => 'integer',
						'description' => 'WordPress post ID to save meta description for',
					),
					'meta_description' => array(
						'type'        => 'string',
						'description' => 'Generated meta description text (150-160 characters)',
					),
				),
				'required'             => array( 'post_id', 'meta_description' ),
				'additionalProperties' => false,
			),
		);
	}

	/**
	 * Execute the save_meta_description tool.
	 *
	 * @param array $args Tool arguments.
	 * @return string JSON response or error message.
	 */
	public static function run( array $args ): string {
		if ( ! function_exists( 'get_post' ) || ! function_exists( 'update_post_meta' ) ) {
			return 'ERROR: wp_functions_unavailable';
		}

		$post_id          = isset( $args['post_id'] ) ? (int) $args['post_id'] : 0;
		$meta_description = isset( $args['meta_description'] ) ? trim( $args['meta_description'] ) : '';

		if ( $post_id <= 0 ) {
			return 'ERROR: invalid_post_id';
		}

		$post = get_post( $post_id );
		if ( ! $post || 'trash' === $post->post_status || 'auto-draft' === $post->post_status ) {
			return 'ERROR: post_not_found';
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return 'ERROR: insufficient_permissions';
		}

		$sanitized_description = sanitize_text_field( wp_strip_all_tags( $meta_description ) );

		if ( empty( $sanitized_description ) ) {
			return 'ERROR: empty_meta_description';
		}

		$description_length = strlen( $sanitized_description );
		$length_warning     = '';

		if ( $description_length > 160 ) {
			$length_warning = 'Meta description exceeds 160 characters and may be truncated in search results';
		} elseif ( $description_length < 120 ) {
			$length_warning = 'Meta description is shorter than recommended (120-160 characters)';
		}

		$existing_description = get_post_meta( $post_id, '_agenticwp_meta_description', true );
		$is_update            = ! empty( $existing_description );

		$save_result = update_post_meta( $post_id, '_agenticwp_meta_description', $sanitized_description );

		if ( false === $save_result ) {
			return 'ERROR: save_failed';
		}

		$response = array(
			'success'              => true,
			'post_id'              => $post_id,
			'post_title'           => $post->post_title,
			'meta_description'     => $sanitized_description,
			'description_length'   => $description_length,
			'action'               => $is_update ? 'updated' : 'created',
			'previous_description' => $is_update ? $existing_description : null,
		);

		if ( ! empty( $length_warning ) ) {
			$response['warning'] = $length_warning;
		}

		return wp_json_encode( $response );
	}
}
