<?php
/**
 * Class Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Helpers
 */

namespace Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API;

use Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Enums\Content_Role;
use Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Types\Candidates;
use Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Types\Content;
use Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Types\Parts\Text_Part;
use Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\Util\Formatter;
use Generator;

/**
 * Class providing static helper methods as part of the public API.
 */
final class Helpers {

	/**
	 * Converts a Content instance to a text string.
	 *
	 * This method will return the combined text from all consecutive text parts in the content.
	 * Realistically, this should almost always return the text from just one part, as API responses typically do not
	 * contain multiple text parts in a row - but it might be possible.
	 *
	 * @param Content $content The content instance.
	 * @return string The text, or an empty string if there are no text parts.
	 */

	public static function content_to_text( Content $content ): string {
		$parts = $content->get_parts();
	
		// Convert parts to array using to_array()
		$partsArray = $parts->to_array();
	
		$text_parts = [];
	
		// Loop through the array and access text data
		foreach ($partsArray as $partData) {
			if (isset($partData['text'])) {
				// Collect the text data into the $text_parts array
				$text_parts[] = $partData['text'];
			}
		}
	
		// If no text parts are found, return an empty string
		if (count($text_parts) === 0) {
			return '';
		}
	
		// Return the concatenated text parts with double new lines between them
		return implode("\n\n", $text_parts);
	}

	/**
	 * Gets the text from the first Content instance in the given list which contains text.
	 *
	 * @param Content[] $contents The list of Content instances.
	 * @return string The text, or an empty string if no Content instance has text parts.
	 */
	public static function get_text_from_contents( array $contents ): string {
		foreach ( $contents as $content ) {
			$text = self::content_to_text( $content );			
			if ( '' !== $text ) {
				return $text;
			}
		}
		return '';
	}

	/**
	 * Gets the Content instances for each candidate in the given list.
	 *
	 * @param Candidates|Loco_Automatic_Translate_Addon_Pro\AI_Translate\Services\API\Types\Candidates $candidates The list of candidates.
	 * @return Content[] The list of Content instances.
	 */
	public static function get_candidate_contents(Candidates $candidates ): array {
		$contents = array();

		foreach ( $candidates as $candidate ) {
			$content = $candidate->get_content();
			if ( ! $content ) {
				continue;
			}
			$contents[] = $content;
		}

		return $contents;
	}
}
