<?php

namespace Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\Chat_Completion;

use Limb_Chatbot\Includes\Data_Objects\Tool_Result_Message as Parent_Tools_Result_Message;

/**
 * Class Tool_Result_Message
 *
 * Represents the result of a tool call in Claude's message format.
 *
 * Claude expects tool results as content blocks with type "tool_result".
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Claude\Endpoints\Chat_Completion
 * @since 1.0.9
 */
class Tool_Result_Message extends Parent_Tools_Result_Message {

	/**
	 * Array of tool result content blocks.
	 *
	 * @var array
	 * @since 1.0.9
	 */
	public array $tool_results = array();

	/**
	 * Add a tool result to the message.
	 *
	 * @param  string  $tool_use_id  The ID of the tool use this result corresponds to.
	 * @param  mixed  $content  The result content (string or array).
	 * @param  bool  $is_error  Whether this result represents an error.
	 *
	 * @return self
	 * @since 1.0.9
	 */
	public function add_result( string $tool_use_id, $content, bool $is_error = false ): self {
		$result = array(
			'type'        => 'tool_result',
			'tool_use_id' => $tool_use_id,
			'content'     => is_string( $content ) ? $content : wp_json_encode( $content ),
		);

		if ( $is_error ) {
			$result['is_error'] = true;
		}

		$this->tool_results[] = $result;

		return $this;
	}

	/**
	 * Get the content blocks for the API request.
	 *
	 * @return array Array of tool_result content blocks.
	 * @since 1.0.9
	 */
	public function get_content_blocks(): array {
		return $this->tool_results;
	}

	/**
	 * Get the role for this message.
	 *
	 * Tool results are sent as user messages in Claude.
	 *
	 * @return string The role (always 'user' for tool results in Claude).
	 * @since 1.0.9
	 */
	public function get_role(): string {
		return 'user';
	}

	/**
	 * Get the tool use ID (for compatibility with OpenAI format).
	 *
	 * Returns the first tool use ID if available.
	 *
	 * @return string|null The tool use ID or null.
	 * @since 1.0.9
	 */
	public function get_tool_call_id(): ?string {
		if ( ! empty( $this->tool_results[0]['tool_use_id'] ) ) {
			return $this->tool_results[0]['tool_use_id'];
		}

		return null;
	}

	/**
	 * Create a Tool_Result_Message from simple parameters.
	 *
	 * For compatibility with OpenAI's tool result format.
	 *
	 * @param  string  $tool_call_id  The tool call ID.
	 * @param  mixed  $content  The result content.
	 * @param  bool  $is_error  Whether this is an error result.
	 *
	 * @return self
	 * @since 1.0.9
	 */
	public static function from_tool_call( string $tool_call_id, $content, bool $is_error = false ): self {
		$instance = self::make( array(
			'role' => 'user',
		) );

		$instance->add_result( $tool_call_id, $content, $is_error );

		return $instance;
	}
}

