<?php
/**
 * Message array helpers used by the agent loop.
 *
 * @package Niwa_AI
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Niwa_AI_Agent_Message_Utils {

	public static function strip_duplicate_runtime_system_message( $messages, $instructions ) {
		if ( ! is_array( $messages ) || empty( $messages ) ) {
			return array();
		}

		$first = isset( $messages[0] ) && is_array( $messages[0] ) ? $messages[0] : array();
		$role  = isset( $first['role'] ) ? strtolower( trim( (string) $first['role'] ) ) : '';

		if ( 'system' !== $role ) {
			return $messages;
		}

		$content = isset( $first['content'] ) ? trim( (string) $first['content'] ) : '';
		if ( '' === $content || trim( (string) $instructions ) !== $content ) {
			return $messages;
		}

		array_shift( $messages );
		return array_values( $messages );
	}

	public static function extract_last_assistant_content( $agent_context ) {
		$messages = $agent_context->get_messages();

		for ( $i = count( $messages ) - 1; $i >= 0; $i-- ) {
			$msg = $messages[ $i ];

			if ( 'assistant' !== ( isset( $msg['role'] ) ? $msg['role'] : '' ) ) {
				continue;
			}

			$content = isset( $msg['content'] ) ? $msg['content'] : '';

			if ( is_string( $content ) && '' !== trim( $content ) ) {
				return trim( $content );
			}

			if ( is_array( $content ) ) {
				$parts = array();
				foreach ( $content as $part ) {
					if ( is_array( $part ) && isset( $part['type'] ) && 'text' === $part['type'] && ! empty( $part['text'] ) ) {
						$parts[] = (string) $part['text'];
					}
				}

				$text = trim( implode( "\n", $parts ) );

				if ( '' !== $text ) {
					return $text;
				}
			}
		}

		return '';
	}
}
