<?php

namespace Limb_Chatbot\Includes\Chatbot_Tools\Tools;

use Limb_Chatbot\Includes\Chatbot_Tools\Chatbot_Tool;
use Limb_Chatbot\Includes\Data_Objects\Tool_Calls_Message;
use Limb_Chatbot\Includes\Services\Live_Agent_Service;
use Limb_Chatbot\Includes\Utilities\Chatbot_Utility;

/**
 * Live Agent Connection Tool
 *
 * Connects the chat to a live agent through configured integration (Slack, Telegram, etc.).
 * This tool never responds to the LLM - it only sets flags and triggers the live agent connection.
 *
 * @package Limb_Chatbot\Includes\Chatbot_Tools\Tools
 * @since 1.0.0
 */
class Live_Agent_Connection extends Chatbot_Tool {

	/**
	 * Define the tool's internal name.
	 *
	 * @return string Tool name.
	 * @since 1.0.0
	 */
	protected function define_name(): string {
		return 'connect_live_agent';
	}

	/**
	 * Define the tool's description for the AI.
	 *
	 * @return string Tool description.
	 * @since 1.0.0
	 */
	protected function define_description(): string {
		return 'Connect the user to a live support agent. Use this when the user explicitly requests human assistance, when their issue requires human intervention, or when the conversation needs to be escalated to a live person.';
	}

	/**
	 * Define the parameters schema for the tool.
	 *
	 * @return array Parameters schema.
	 * @since 1.0.0
	 */
	protected function define_parameters_schema(): array {
		return [
			'type'       => 'object',
			'properties' => [
				'reason' => [
					'type'        => 'string',
					'description' => 'Brief reason for connecting to a live agent (e.g., "user requested human help", "technical issue", "sales inquiry")',
				],
			],
			'required'   => [ 'reason' ],
		];
	}

	/**
	 * Execute the live agent connection.
	 *
	 * This returns an empty array as the tool should NOT respond to the LLM.
	 * All side effects (chat meta updates, Slack notifications) happen internally.
	 *
	 * @param array              $params  Tool parameters.
	 * @param Tool_Calls_Message $message Original message that triggered the tool.
	 * @param Chatbot_Utility    $utility Chatbot utility instance.
	 *
	 * @return array Empty array - no response to LLM.
	 * @since 1.0.0
	 */
	public function execute( array $params, Tool_Calls_Message $message, Chatbot_Utility $utility ): array {
		$chat = $utility->get_chat();
		if ( ! $chat ) {
			return [];
		}

		try {
			$service = new Live_Agent_Service();
			$service->connect_live_agent( $chat, $utility, $params['reason'] ?? '' );
		} catch ( \Exception $e ) {
			// Silently handle errors - don't break the conversation
			error_log( sprintf( 'Live agent connection failed: %s', $e->getMessage() ) );
		}

		// Return empty array - no response to LLM
		return [];
	}
}

