<?php

namespace Limb_Chatbot\Includes\AI_Providers\Grok\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 xAI's message format.
 *
 * xAI uses OpenAI-compatible format with role 'tool'.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Grok\Endpoints\Chat_Completion
 * @since 1.0.12
 */
class Tool_Result_Message extends Parent_Tools_Result_Message {

	/**
	 * The tool call ID this result corresponds to.
	 *
	 * @var string
	 * @since 1.0.12
	 */
	public string $tool_call_id = '';

	/**
	 * Get the tool call ID.
	 *
	 * @return string The tool call ID.
	 * @since 1.0.12
	 */
	public function get_tool_call_id(): string {
		return $this->tool_call_id;
	}

	/**
	 * Set the tool call ID.
	 *
	 * @param  string  $tool_call_id  The tool call ID.
	 *
	 * @return self
	 * @since 1.0.12
	 */
	public function set_tool_call_id( string $tool_call_id ): self {
		$this->tool_call_id = $tool_call_id;

		return $this;
	}

	/**
	 * Get the result content as string.
	 *
	 * Helper method to get content as string for API requests.
	 *
	 * @return string The result content.
	 * @since 1.0.12
	 */
	public function get_content_string(): string {
		$content = $this->get_content();

		if ( is_array( $content ) ) {
			// Extract text from content array if needed
			if ( isset( $content[0]['text']['value'] ) ) {
				return $content[0]['text']['value'];
			}
			return wp_json_encode( $content );
		}

		return (string) $content;
	}

	/**
	 * Set the result content.
	 *
	 * @param  mixed  $content  The result content (string or array).
	 *
	 * @return self
	 * @since 1.0.12
	 */
	public function set_result_content( $content ): self {
		// Store content in parent's content property in the expected format
		$formatted_content = is_string( $content ) ? $content : wp_json_encode( $content );

		$this->content = array(
			array(
				'type' => 'text',
				'text' => array( 'value' => $formatted_content ),
			),
		);

		return $this;
	}

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

	/**
	 * Create a Tool_Result_Message from a tool call.
	 *
	 * @param  string  $tool_call_id  The tool call ID.
	 * @param  mixed  $content  The result content.
	 *
	 * @return self
	 * @since 1.0.12
	 */
	public static function from_tool_call( string $tool_call_id, $content ): self {
		$instance = self::make( array(
			'role' => 'tool',
		) );

		$instance->set_tool_call_id( $tool_call_id );
		$instance->set_result_content( $content );

		return $instance;
	}
}


