<?php

namespace Limb_Chatbot\Includes\AI_Providers\Open_Ai\Services;

use Limb_Chatbot\Includes\Data_Objects\Dataset;
use Limb_Chatbot\Includes\Data_Objects\Dataset_Entry;
use Limb_Chatbot\Includes\Interfaces\Fine_Tuning_File_Formatting_Interface;
use Limb_Chatbot\Includes\Services\Fine_Tuning_File_Formatting_Service as Global_Fine_Tuning_File_Formatting_Service;

/**
 * Class Fine_Tuning_File_Formatting_Service
 *
 * Handles the formatting of dataset entries into a JSON structure
 * compatible with OpenAI’s fine-tuning input expectations.
 *
 * @package Limb_Chatbot\Includes\AI_Providers\Open_Ai\Services
 * @since 1.0.0
 */
class Fine_Tuning_File_Formatting_Service extends Global_Fine_Tuning_File_Formatting_Service implements Fine_Tuning_File_Formatting_Interface {

	/**
	 * Formats a single dataset entry into a structured JSON line
	 * suitable for OpenAI fine-tuning with assistant-style message roles.
	 *
	 * It includes optional `system` prompts, `user` messages, and
	 * `assistant` responses. Optionally includes `weight` for responses.
	 *
	 * @param Dataset_Entry $dataset_entry The individual entry to format.
	 * @param Dataset|null $dataset Optional parent dataset used to fallback to global instructions.
	 *
	 * @return string A JSON-encoded string representing the entry in messages format.
	 * @since 1.0.0
	 */
	public function prepare_message_row( Dataset_Entry $dataset_entry, ?Dataset $dataset = null ): string {
		$array          = [];
		$system_message = ! empty( $dataset_entry->get_entry()['system'] ) ? $dataset_entry->get_entry()['system'] : $dataset->get_instruction();
		if ( $system_message ) {
			$array['messages'][] = [ 'role' => 'system', 'content' => $system_message ];
		}
		foreach ( $dataset_entry->entry['messages'] as $message ) {
			$output_arr = [ 'role' => 'assistant', 'content' => $message['output'], ];
			if ( ! empty( $message['weight'] ) ) {
				$output_arr['weight'] = $message['weight'];
			}
			$array['messages'][] = [ 'role' => 'user', 'content' => $message['input'], ];
			$array['messages'][] = $output_arr;
		}

		return json_encode( $array );
	}
}