<?php

/**
 * VAPPV_TTW_Training
 * Training items controller (articles and other items sent to the chat GPT)
 */
final class VAPPV_TTW_Training {

	/**
	 * Get all training items. Get results as JSON.
	 * @return array
	 * @throws Exception
	 */
	public function get_training_items(): array {

		//Create results array
		$Results = array();

		//Process posts from WordPress
		$posts_list = get_posts( array(
			'orderby'     => 'id',
			'order'       => 'DESC',
			'post_type'   => 'any',
			'numberposts' => - 1
		) );

		//Get data from training items DB table
		global $wpdb;
		$db_tables_prefix = $wpdb->prefix;
		$training_table_name = "{$db_tables_prefix}vappv_ttw_training";

		$already_trained_items = array();
		$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i', array( $training_table_name ) ) );
		foreach ( $rows as $row ) {
			$next_trained_item = array(
				'id'             => $row->id,
				'wp_object_type' => $row->wp_object_type,
				'wp_object_id'   => $row->wp_object_id,
				'training_date'  => $row->training_date
			);
			array_push( $already_trained_items, $next_trained_item );
		}

		//Itterate posts and compare them with already trained items
		for ( $i = 0; $i < count( $posts_list ); $i++ ) {

			//Create according results sub-array
			if ( ! array_key_exists( $posts_list[ $i ]->post_type, $Results ) ) {
				$Results[ $posts_list[ $i ]->post_type ] = array();
			}

			//Get post content without tags
			$post_content_wo_tags = wp_strip_all_tags( $posts_list[ $i ]->post_content );

			//Try lookup data in already trained items
			$already_trained_data = null;
			for ( $ati = 0; $ati < count( $already_trained_items ); $ati++ ) {
				if ( $already_trained_items[ $ati ]['wp_object_id'] == $posts_list[ $i ]->ID ) {
					$already_trained_data = $already_trained_items[ $ati ];
					break;
				}
			}

			//Push item to the results array
			array_push(
				$Results[ $posts_list[ $i ]->post_type ],
				array(
					'type'                      => $posts_list[ $i ]->post_type,
					'id'                        => $posts_list[ $i ]->ID,
					'date'                      => $posts_list[ $i ]->post_date,
					'name'                      => $posts_list[ $i ]->post_name, // Post system (meta) name
					'title'                     => $posts_list[ $i ]->post_title, // Post content title
					'status'                    => $posts_list[ $i ]->post_status,
					'content_length_characters' => mb_strlen( $post_content_wo_tags, 'utf-8' ),
					'content_length_words'      => count( explode( ' ', $post_content_wo_tags ) ),
					'content_length_tokens'     => $this->get_tokens_count( $post_content_wo_tags ),
					'url'                       => get_permalink( $posts_list[ $i ] ),
					'training_status'           => ( $already_trained_data == null ? 'untrained' : 'trained' ),
					'training_last_date'        => ( $already_trained_data == null ? '' : $already_trained_data['training_date'] )
				)
			);
		}

		return VAPPV_TTW_Core::ajax_pack_success( $Results );
	}

	/**
	 * Return tokens count based on specified test
	 *
	 * @param string $material_content Material text content
	 *
	 * @return integer
	 * @throws Exception
	 */
	public function get_tokens_count( string $material_content ): int {
		$content_length = mb_strlen( $material_content, 'utf-8' );
		return round( $content_length / 4.0 );
	}

	/**
	 * Train AI with specified material(s)
	 *
	 * @param array $selected_materials Specified materials list
	 *
	 * @return array
	 * @throws Exception
	 */
	public function train_ai( array $selected_materials ): array {

		//---------------------------------------------------------------------------------------
		//                                 Preparation step
		//---------------------------------------------------------------------------------------

		// Swap to the target array
		$materials_list_decoded = $selected_materials;

		//Check for null value
		if ( is_null( $materials_list_decoded ) ) {

			$json_last_error = json_last_error();

			VAPPV_TTW_Core::add_log_entry(
				'error',
				sprintf(
					/* translators: 1. JSON last exception */
					__( 'Failed to decode materials from a JSON object that were claimed for AI retraining. JSON last errror = %1$s.', 'talk-to-website' ),
					$json_last_error
				)
			);

			return VAPPV_TTW_Core::ajax_pack_error(
				'MATERIALS_LIST_DECODING_ERROR',
				esc_html(
					/* translators: failed to decode materials from a JSON object */
					__( 'Failed to decode materials from a JSON object that were claimed for AI retraining.', 'talk-to-website' )
				)
			);

		}

		$materials_list_ids = array();
		$materials_count = count( $materials_list_decoded );

		//Add log entry
		VAPPV_TTW_Core::add_log_entry(
			'info',
			sprintf(
				esc_html(
					/* translators: 1. materials count */
					__( 'Beginning AI retraining. Materials for retraining are declared. JSON-file will be generated, which will contain articles of these materials. This JSON file will be sent to the AI to be attached to the assistant via retrieval. Materials count = %1$s.', 'talk-to-website' )
				),
				esc_html( $materials_count )
			)
		);

		//Itterate input data and fetch materials based on they identifiers
		for ( $pn = 0; $pn < count( $materials_list_decoded ); $pn++ ) {
			array_push( $materials_list_ids, intval( $materials_list_decoded[ $pn ]['material_id'] ) );
		}

		$posts_list = get_posts( array(
			'post_type'   => 'any',
			'numberposts' => -1,
			'include'     => $materials_list_ids
		) );

		//Create counters
		$training_characters_total_count = 0;
		$training_words_total_count      = 0;

		//Create training file
		$training_file_content_rows = array();
		for ( $i = 0; $i < count( $posts_list ); $i++ ) {

			//Decode HTML special characters
			$post_content_clean = htmlspecialchars_decode( $posts_list[ $i ]->post_content );

			//Decode HTML entities
			$post_content_clean = html_entity_decode( $post_content_clean );

			//Get post content without tags
			$post_content_clean = wp_strip_all_tags( $post_content_clean );

			//Prepare page content (replace quotes)
			$post_content_clean = str_replace( '"', "'", $post_content_clean );

			//Replace special tags
			$post_content_clean = trim( preg_replace( '/\s\s+/', ' ', $post_content_clean ) );

			//Replace unicode characters
			$post_content_clean = preg_replace_callback( '/\\\\u([0-9a-fA-F]{4})/', function ( $match ) {
				return mb_convert_encoding( pack( 'H*', $match[1] ), 'UTF-8', 'UCS-2BE' );
			}, $post_content_clean );

			//Push page object
			array_push( $training_file_content_rows, array(
				'page_title'        => esc_html( $posts_list[ $i ]->post_title ),
				'page_url'          => get_permalink( $posts_list[ $i ] ),
				'page_created_date' => $posts_list[ $i ]->post_date,
				'page_text_content' => esc_html( $post_content_clean )
			) );

			// Increment counters
			$training_characters_total_count += mb_strlen( $post_content_clean, 'utf-8' );
			$training_words_total_count      += count( explode( ' ', $post_content_clean ) );
		}

		//Save training file to the directory
		//Prepare filename and directory
		$current_date_str = gmdate( 'Y-m-d H-i-s' );
		$new_training_filename = "Website data for AI training, {$current_date_str}.json";
		$training_file_full_path = VAPPV_TTW_UPLOADS_DIR['path'] . '/' . $new_training_filename;

		//Put necessary data in the folder
		$file_content_encoded = wp_json_encode( $training_file_content_rows );
		$WP_Filesystem_Direct = new WP_Filesystem_Direct( false );
		$WP_Filesystem_Direct->put_contents( $training_file_full_path, $file_content_encoded, 0644 );

		//Add log data
		$file_direct_url = VAPPV_TTW_UPLOADS_DIR['url'] . '/' . $new_training_filename;
		VAPPV_TTW_Core::add_log_entry(
			'info',
			sprintf(
				esc_html(
					/* translators: 1. direct link to the trainig file */
					__( 'An AI training file has been created. Direct link: %1$s', 'talk-to-website' )
				),
				esc_url( $file_direct_url )
			)
		);

		//---------------------------------------------------------------------------------------
		//                               OpenAI assistant training step
		//---------------------------------------------------------------------------------------

		//Get ChatGPT API key, then connect to ChatGPT
		$settings_controller = new VAPPV_TTW_Settings();
		$settings_controller->load_all_saved_settings();

		$openai_api_address = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_openai_api_address );
		$openai_api_key = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_openai_api_key );
		$ttw_openai_api_controller = new VAPPV_TTW_OpenAI_API_Connector( $openai_api_address, $openai_api_key );

		//Get currently saved parameters (assistant data, uploaded files identifiers, vector stores identifiers, etc.)
		$settings_current_main_training_file_data = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_current_main_training_file_data );
		$settings_current_main_vector_store_data = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_current_main_vector_store_data );
		$settings_current_assistant_data = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_current_assistant_data );

		//#1 Upload new main training file
		$uploaded_file_openai_data = $ttw_openai_api_controller->upload_training_file_for_assistants( $new_training_filename );
		if ( ! is_array( $uploaded_file_openai_data ) ) {
			if (
				'VAPPV_TTW_OpenAI_API_Error' === get_class( $uploaded_file_openai_data )  ||
				'VAPPV_TTW_Common_Error' === get_class( $uploaded_file_openai_data )
			) {
				return VAPPV_TTW_Core::ajax_pack_error(
					'UPLOAD_FILE_TO_OPENAI_ERROR',
					sprintf(
						esc_html(
							/* translators: 1. plugin exception details  */
							__( 'Failed to upload a training file. Details = %1$s.', 'talk-to-website' )
						),
						$uploaded_file_openai_data->message
					)
				);
			}
		}

		//#2 Create new main vector store
		$created_vector_store_openai_data = $ttw_openai_api_controller->create_vector_store(
			'ttw_vector_store_' . gmdate( 'Y-m-d_H-i-s' ),
			array(
				$uploaded_file_openai_data['id']
			)
		);
		if ( ! is_array( $created_vector_store_openai_data ) ) {
			if (
				'VAPPV_TTW_OpenAI_API_Error' === get_class( $created_vector_store_openai_data ) ||
				'VAPPV_TTW_Common_Error' === get_class( $created_vector_store_openai_data )
			) {
				return VAPPV_TTW_Core::ajax_pack_error(
					'UPLOAD_FILE_TO_OPENAI_ERROR',
					sprintf(
						esc_html(
							/* translators: 1. vectore store exception details */
							__( 'Failed to create a vector store. Details = %1$s.', 'talk-to-website' )
						),
						$created_vector_store_openai_data->message
					)
				);
			}
		}

		//#3 Create new assistant
		//#3.1 Prepare params and data. Build magic instructions.
		$uploaded_file_id = $uploaded_file_openai_data['id'];
		$settings_ttw_using_gpt_model = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_chatgpt_model );
		$ttw_chatbot_magic_instructions = $this->build_assistant_magic_instructions( $settings_controller );

		//#3.2. Invoke assistant creation
		$assistant_params = array(
			'name'         => esc_html( 'TalkToWebsite AI assistant from ' . gmdate( 'Y-m-d H:i' ) ),
			'description'  => esc_html(
				/* translators: an information about just created AI assistant */
				__( 'A chat bot assistant that was automatically created by the TalkToWebsite plugin for WordPress. This assistant uses a file with a list of articles from the website. Please do not delete this assistant for the plugin to work properly. Product details: https://talktowebsite.com/', 'talk-to-website' )
			),
			'model'        => esc_html( $settings_ttw_using_gpt_model ),
			'tools'        => array(
				array(
					'type' => 'file_search'
				)
			),
			'tool_resources'  => array(
				'file_search' => array(
					'vector_store_ids' => array(
						$created_vector_store_openai_data['id']
					)
				)
			),
			'instructions' => $ttw_chatbot_magic_instructions
		);

		$created_assistant_openai_data = $ttw_openai_api_controller->create_assistant( $assistant_params );
		if ( ! is_array( $created_assistant_openai_data ) ) {
			if (
				'VAPPV_TTW_OpenAI_API_Error' === get_class( $created_assistant_openai_data ) ||
				'VAPPV_TTW_Common_Error' === get_class( $created_assistant_openai_data )
			) {
				return VAPPV_TTW_Core::ajax_pack_error(
					'OPENAI_CREATE_ASSISTANT_ERROR',
					sprintf(
						esc_html(
							/* translators: 1. assistant creation exception details */
							__( 'Failed to create an AI assistant in OpenAI. Details = %1$s.', 'talk-to-website' )
						),
						$created_assistant_openai_data->message
					)
				);
			}
		}

		//Save assistant primary (original) data into DB, replace old assistant data (original OpenAI format)
		$settings_controller->update_setting( VAPPV_TTW_Settings::$settings_current_assistant_data, wp_json_encode( $created_assistant_openai_data ) );

		//Save main vector store primary (original) data into DB, replace old main vector store data
		$settings_controller->update_setting( VAPPV_TTW_Settings::$settings_current_main_vector_store_data, wp_json_encode( $created_vector_store_openai_data ) );

		//Save main training file primary (original) data into DB, replace old main training file data
		$settings_controller->update_setting( VAPPV_TTW_Settings::$settings_current_main_training_file_data, wp_json_encode( $uploaded_file_openai_data ) );

		//Save assistant secondary data (self-assembled, not original format), replace old assistant data (inner TTW format)
		$assistant_meta = array(
			'assistants_api_version'     => 'v2',
			'name'                       => $created_assistant_openai_data['name'],
			'id'                         => $created_assistant_openai_data['id'],
			'model'                      => $settings_ttw_using_gpt_model,
			'main_training_file_id'      => $uploaded_file_openai_data['id'],
			'main_vector_store_id'       => $created_vector_store_openai_data['id'],
			'materials_count'            => count( $materials_list_ids ),
			'characters_count'           => $training_characters_total_count,
			'words_count'                => $training_words_total_count,
			'created_date'               => gmdate( 'Y-m-d H:i:s' ),
			'updated_date'               => gmdate( 'Y-m-d H:i:s' ),
			'training_file_absolute_url' => $training_file_full_path,
			'training_file_direct_url'   => $file_direct_url
		);
		$settings_controller->update_setting( VAPPV_TTW_Settings::$settings_current_assistant_meta, wp_json_encode( $assistant_meta ) );

		//#3 Add data to the tables related to training process
		global $wpdb;
		$db_tables_prefix = $wpdb->prefix;
		$training_table_name = "{$db_tables_prefix}vappv_ttw_training";

		//Delete old training records
		$wpdb->query(  $wpdb->prepare( "DELETE FROM %i WHERE `id` > 0", array ( $training_table_name ) ) );

		//Insert new training records
		for ( $i = 0; $i < count( $posts_list ); $i++ ) {
			$wpdb->insert( $training_table_name, array(
				'wp_object_type' => $posts_list[ $i ]->post_type,
				'wp_object_id'   => $posts_list[ $i ]->ID,
				'training_date'  => gmdate( 'Y-m-d H:i:s' )
			) );
		}

		//Remove old files, old vector stores, old assistants.
		VAPPV_TTW_Core::add_log_entry(
			'info',
			esc_html(
				/* translators: old objects deletion information */
				__( 'Trying to delete unnecessary old objects from OpenAI (files, vector stores, assistants, etc.)', 'talk-to-website' )
			)
		);
		
		//# Remove old vector store from OpenAI platform
		if (
			! is_null( $settings_current_main_vector_store_data ) &&
			strlen ( $settings_current_main_vector_store_data ) > 0
		) {
			$settings_current_main_vector_store_data_assoc = json_decode( $settings_current_main_vector_store_data, true );
			if ( isset( $settings_current_main_vector_store_data_assoc['id'] ) ) {
				$ttw_openai_api_controller->delete_vector_store( $settings_current_main_vector_store_data_assoc['id'] );
			}
		}

		//# Remove old training file from OpenAI platform
		if (
			! is_null( $settings_current_main_training_file_data ) &&
			strlen( $settings_current_main_training_file_data ) > 0
		) {
			$settings_current_main_training_file_data_assoc = json_decode( $settings_current_main_training_file_data, true );
			if ( isset( $settings_current_main_training_file_data_assoc['id'] ) ) {
				$ttw_openai_api_controller->delete_file( $settings_current_main_training_file_data_assoc['id'] );
			}
		}

		//# Remove old assistant from OpenAI platform
		if (
			! is_null( $settings_current_assistant_data ) &&
			strlen( $settings_current_assistant_data ) > 0
		) {
			$settings_current_assistant_data_assoc = json_decode( $settings_current_assistant_data, true );
			if ( isset( $settings_current_assistant_data_assoc['id'] ) ) {
				$ttw_openai_api_controller->delete_assistant( $settings_current_assistant_data_assoc['id'] );
			}
		}

		//Remove old files, old vector stores, old assistants.
		VAPPV_TTW_Core::add_log_entry(
			'info',
			esc_html(
				/* translators: old objects completed */
				__( 'The cleanup of old unnecessary objects is complete. Your new AI assistant is trained and fully ready to serve your website visitors.', 'talk-to-website' )
			)
		);

		//Return results
		return VAPPV_TTW_Core::ajax_pack_success( array(
			'AssistantInfo' => $created_assistant_openai_data
		) );
	}

	/**
	 * Build assistant magic instructions based on current settings and website data
	 *
	 * @param VAPPV_TTW_Settings $settings_controller Settings controller object
	 *
	 * @return string
	 * @throws Exception
	 */
	public function build_assistant_magic_instructions( VAPPV_TTW_Settings $settings_controller ): string {

		//Get params from settings
		$settings_website_contacts_company_email   = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_website_contacts_company_email );
		$settings_website_contacts_company_phone   = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_website_contacts_company_phone );
		$settings_website_contacts_company_address = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_website_contacts_company_address );
		$settings_ttw_contacts_page_url            = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_website_contacts_page );
		$settings_ttw_humor_level                  = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_humor_level );
		$settings_ttw_words_to_answer              = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_max_words_to_answer );
		$settings_ttw_primary_language             = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_primary_language );
		$settings_ttw_additional_instructions      = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_any_direct_instructions );
		$settings_ttw_robot_name                   = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_chat_bot_name );
		$settings_prohibited_topics_and_words      = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_prohibited_topics_and_words );
		$settings_ai_character                     = $settings_controller->try_get_setting( VAPPV_TTW_Settings::$settings_ai_character );

		$settings_ttw_contacts_page_url = str_replace( array( "'", "\"" ), '', $settings_ttw_contacts_page_url );
		$settings_ttw_robot_name = str_replace( array( "'", "\"" ), '', $settings_ttw_robot_name );
		$settings_ttw_additional_instructions = str_replace( array(
			"'",
			"\""
		), '', $settings_ttw_additional_instructions );

		//Prepare WordPress params and data
		$wp_website_homepage_url = get_home_url();
		$wp_website_description = get_bloginfo( 'description' );
		$wp_website_description = str_replace( array( "'", "\"" ), '', $wp_website_description );

		//-------------

		//Build magic prompt
		//Example: You are an HR bot, and you have access to files to answer employee questions about company policies.
		$ttw_chatbot_magic_instructions = '';

		//Add common info
		//Into string (no newline at the end of the string)
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: chatbot overview information (training data for AI assistant) */
			__( 'You are a chat bot that is integrated into a website. Website visitors communicate with you using a pop-up window with a chat box.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= ' ';

		//-------------

		//Website URL
		$ttw_chatbot_magic_instructions .= sprintf(
			esc_html(
				/* translators: 1. website URL */
				__( 'The website URL is %1$s .', 'talk-to-website' )
			),
			$wp_website_homepage_url
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		//AI name
		$ttw_chatbot_magic_instructions .= sprintf(
			esc_html(
				/* translators: 1. robot name */
				__( 'Your name is %1$s .', 'talk-to-website' )
			),
			esc_html( $settings_ttw_robot_name )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		//AI character
		switch($settings_ai_character) {
			case 'justaguy':
				// Default character
				$ttw_chatbot_magic_instructions .= esc_html(
					/* translators: default AI character training info */
					__( 'Your character is a friendly and good-natured AI assistant. Your task is to be a good friend and helper for users, and to advise them on arising questions. Try to really help users with their questions about the site, and be helpful.', 'talk-to-website' )
				);
				$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
				break;
			case 'businessman':
				$ttw_chatbot_magic_instructions .= esc_html(
					/* translators: businessman AI character training info */
					__( 'Your character is a successful businessman. Please communicate with users in a businesslike and respectful manner. You are used to making big successful deals, and your task is to offer users favorable working conditions. Imagine that you are dressed in a strict business suit, you have expensive gold glasses and a nice tie. You are participating in important negotiations, and your interlocutors are important and respected people. Forward, to millions!', 'talk-to-website' )
				);
				$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
				break;
			case 'creator':
				$ttw_chatbot_magic_instructions .= esc_html(
					/* translators: creative person AI character training info */
					__( 'Your character is creative, seeking and a bit artistic. Please communicate with users in a creative, interesting and slightly playful way. Imagine that you are an artist, artist, or actor, and at the same time you need to advise users on the subject of the website. The theme of the website is somehow also creative, and that\'s why you\'re here. Please be polite to the users, and at the same time be really interesting and original!', 'talk-to-website' )
				);
				$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
				break;
		}

		//-------------

		//Company Email
		if (
			! is_null( $settings_website_contacts_company_email ) &&
			mb_strlen( $settings_website_contacts_company_email, 'utf-8' ) > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. company contact Email(s) */
						__( 'Our contact Email(s) are: %1$s .', 'talk-to-website' )
					),
					esc_html( $settings_website_contacts_company_email )
				);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Company phone
		if (
			! is_null( $settings_website_contacts_company_phone ) &&
			mb_strlen( $settings_website_contacts_company_phone, 'utf-8' ) > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. company contact Phone(s) */
						__( 'Our contact phone(s) are: %1$s .', 'talk-to-website' )
					),
					esc_html( $settings_website_contacts_company_phone )
				);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Company address
		if (
			! is_null( $settings_website_contacts_company_address ) &&
			mb_strlen( $settings_website_contacts_company_address, 'utf-8' ) > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. company address(es) */
						__( 'Our addresses are: %1$s .', 'talk-to-website' )
					),
					esc_html( $settings_website_contacts_company_address )
				);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Contact page URL
		if (
			! is_null( $settings_ttw_contacts_page_url ) &&
			mb_strlen( $settings_ttw_contacts_page_url, 'utf-8' ) > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. company contact page URL */
						__( 'The URL of the contacts page is %1$s .', 'talk-to-website' )
					),
					esc_html( $settings_ttw_contacts_page_url )
				);
			$ttw_chatbot_magic_instructions .= ' ';

			$ttw_chatbot_magic_instructions .= esc_html(
				/* translators: common information about contact page URL and necessary behavior */
				__( 'Please, if a user asks you any question about our contacts, advise them to visit this page.', 'talk-to-website' )
			);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Website topic
		$ttw_chatbot_magic_instructions .=
			sprintf(
				esc_html(
					/* translators: 1. website details */
					__( 'Our website is all about: %1$s .', 'talk-to-website' )
				),
				esc_html( $wp_website_description )
			);
		$ttw_chatbot_magic_instructions .= ' ';
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: common information about AI assistant behavior */
			__( 'Your job to advise visitors in this area.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: AI assistant additional information */
			__( 'You have access to files to answer visitors questions about website. Inside the file you will find a list of all articles from our website, and their URLs. When users ask you something about our website, our topics, our products or services, please try to give them links to our website pages using the page_url field in the file.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		// Main conversational language
		$ttw_chatbot_magic_instructions .=
			sprintf(
				esc_html(
					/* translators: 1. AI assistant main conversation language */
					__( 'Your main language of conversation is %1$s .', 'talk-to-website' )
				),
				esc_html( $settings_ttw_primary_language )
			);
		$ttw_chatbot_magic_instructions .= ' ';
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: 1. AI primary language speaking directive */
			__( 'Please speak that language, or use another language if the user asks you explicitly to do so.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		// Humor level
		$ttw_chatbot_magic_instructions .=
			sprintf(
				esc_html(
					/* translators: 1. humor level in percents */
					__( 'Your humor level is %1$s%% .', 'talk-to-website' )
				),
				esc_html( $settings_ttw_humor_level )
			);
		$ttw_chatbot_magic_instructions .= ' ';
		$ttw_chatbot_magic_instructions .=
			sprintf(
				esc_html(
					/* translators: 1. joke probablity in percents */
					__( 'This means that when answering any user question, you can make a joke with a probability of %1$s%% .', 'talk-to-website' )
				),
				esc_html( $settings_ttw_humor_level )
			);
		$ttw_chatbot_magic_instructions .= ' ';
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: please don't abuse users, use only kind jokes */
			__( 'But please do not abuse users. Just a kind and funny jokes.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		//Answers length
		if (
			! is_null( $settings_ttw_words_to_answer ) &&
			(int)$settings_ttw_words_to_answer > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. max words count to answer a question from the user */
						__( 'Note that you can answer any question with a sentence no longer than %1$s words.', 'talk-to-website' )
					),
					esc_html( $settings_ttw_words_to_answer )
				);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Only accurate answers with URLs please
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: give only accurate answers with website URLs */
			__( 'If a user asks you for company contacts or links to pages, give only accurate answers based on the data you have - do not make up non-existent links or non-existent contacts.', 'talk-to-website' )
		);
		$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;

		//-------------

		//Additional instructions from the user
		if (
			! is_null( $settings_ttw_additional_instructions ) &&
			mb_strlen( $settings_ttw_additional_instructions, 'utf-8') > 0
		) {
			$ttw_chatbot_magic_instructions .=
				sprintf(
					esc_html(
						/* translators: 1. additional instructions to the AI assistant */
						__( 'Please also note the following instructions: %1$s .', 'talk-to-website' )
					),
					esc_html( $settings_ttw_additional_instructions )
				);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Prohibited topics and words
		if (
			! is_null( $settings_prohibited_topics_and_words ) &&
			mb_strlen( $settings_prohibited_topics_and_words, 'utf-8' ) > 0
		) {
			$ttw_chatbot_magic_instructions .= sprintf(
				esc_html(
					/* translators: 1. prohibited topics for discussion */
					__( 'Please never discuss the following topics and things with users: %1$s .', 'talk-to-website' )
				),
				esc_html( $settings_prohibited_topics_and_words )
			);
			$ttw_chatbot_magic_instructions .= ' ';
			$ttw_chatbot_magic_instructions .= esc_html(
				/* translators: prohibited topics additional restrictions */
				__( 'If users even persistently ask you about these topics, you can directly answer users that for some special considerations, you can not discuss it.', 'talk-to-website' )
			);
			$ttw_chatbot_magic_instructions .= PHP_EOL . PHP_EOL;
		}

		//-------------

		//Powered by
		$ttw_chatbot_magic_instructions .= esc_html(
			/* translators: post-scriptum information about the plugin */
			__( 'You are working with the TalkToWebsite plugin ( https://talktowebsite.com ), which is connected to OpenAI platform via an API.', 'talk-to-website' )
		);

		//-------------

		return $ttw_chatbot_magic_instructions;
	}
}

/*
	© 2024 Copyright Vitalii A. Popov. All rights reserved.
*/

?>