<?php
/**
 * Finalize_post tool: write buffered content to the post and return edit link.
 *
 * @package AgenticWP
 */

namespace Agentic_WP;

use Agentic_WP\Error_Handler;

defined( 'ABSPATH' ) || exit;

/**
 * Finalize post tool for writing buffered content and returning edit links.
 *
 * @since 1.0.0
 */
class Tool_Finalize_Post {
	/**
	 * Returns the OpenAI tool schema for finalizing a post.
	 *
	 * @since 1.0.0
	 *
	 * @return array Tool schema definition.
	 */
	public static function schema(): array {
		return array(
			'type'        => 'function',
			'name'        => 'finalize_post',
			'description' => 'Finalize a post builder session by writing buffered content and optional excerpt.',
			'strict'      => true,
			'parameters'  => array(
				'type'                 => 'object',
				'properties'           => array(
					'session_id' => array( 'type' => 'string' ),
					'excerpt'    => array( 'type' => 'string' ),
				),
				'required'             => array( 'session_id', 'excerpt' ),
				'additionalProperties' => false,
			),
		);
	}

	/**
	 * Executes the finalize post tool.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args Tool arguments containing session_id and optional excerpt.
	 * @return string JSON response or error message.
	 */
	public static function run( array $args ): string {
		$sid = isset( $args['session_id'] ) && is_string( $args['session_id'] ) ? sanitize_text_field( $args['session_id'] ) : '';
		if ( '' === $sid ) {
			Error_Handler::log_error(
				'tool_finalize_post',
				'Missing session_id'
			);
			return 'ERROR: missing_session_id';
		}
		$session = get_transient( Tool_Start_Post::tkey( $sid ) );
		if ( ! is_array( $session ) || empty( $session['post_id'] ) ) {
			Error_Handler::log_error(
				'tool_finalize_post',
				'Invalid or expired session',
				array( 'session_id' => $sid )
			);
			return 'ERROR: invalid_session';
		}
		$post_id = (int) $session['post_id'];

		$update = array(
			'ID'           => $post_id,
			'post_content' => (string) ( $session['content'] ?? '' ),
		);
		if ( isset( $args['excerpt'] ) && is_string( $args['excerpt'] ) && trim( $args['excerpt'] ) !== '' ) {
			$update['post_excerpt'] = sanitize_text_field( $args['excerpt'] );
		}

		$result = wp_update_post( $update, true );
		if ( is_wp_error( $result ) ) {
			Error_Handler::log_error(
				'tool_finalize_post',
				$result->get_error_message(),
				array(
					'post_id' => $post_id,
					'code'    => $result->get_error_code(),
				)
			);
			return 'ERROR: update_failed';
		}

		delete_transient( Tool_Start_Post::tkey( $sid ) );

		Error_Handler::debug_log(
			'Post finalized',
			array(
				'post_id'    => $post_id,
				'session_id' => $sid,
			)
		);

		$edit_link = (string) get_edit_post_link( $post_id, '' );
		return wp_json_encode(
			array(
				'post_id'   => $post_id,
				'edit_link' => $edit_link,
				'status'    => 'draft',
			)
		);
	}
}
