<?php
/**
 * Builds agent-loop diagnostics for empty model responses.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Agent_Empty_Response_Diagnostic {

	public static function build( $agent_context, $iteration_count, $model, $total_usage ) {
		$messages           = $agent_context->get_messages();
		$message_count      = count( $messages );
		$last_role          = '';
		$last_content       = '';
		$tool_calls_in_last = 0;
		$tool_names         = array();

		for ( $i = $message_count - 1; $i >= 0; $i-- ) {
			$msg  = $messages[ $i ];
			$role = isset( $msg['role'] ) ? (string) $msg['role'] : '';

			if ( '' === $last_role ) {
				$last_role = $role;
			}

			if ( 'assistant' === $role && 0 === $tool_calls_in_last ) {
				$content      = isset( $msg['content'] ) ? $msg['content'] : '';
				$last_content = is_string( $content ) ? mb_substr( $content, 0, 120 ) : '(array)';
				$tc           = isset( $msg['tool_calls'] ) && is_array( $msg['tool_calls'] ) ? $msg['tool_calls'] : array();

				$tool_calls_in_last = count( $tc );
				foreach ( $tc as $tc_item ) {
					$name = '';
					if ( isset( $tc_item['name'] ) ) {
						$name = (string) $tc_item['name'];
					} elseif ( isset( $tc_item['function']['name'] ) ) {
						$name = (string) $tc_item['function']['name'];
					}
					if ( '' !== $name ) {
						$tool_names[] = $name;
					}
				}
				break;
			}
		}

		$prompt_tokens = isset( $total_usage['prompt_tokens'] ) ? intval( $total_usage['prompt_tokens'] ) : 0;
		$comp_tokens   = isset( $total_usage['completion_tokens'] ) ? intval( $total_usage['completion_tokens'] ) : 0;

		$log_line = sprintf(
			'model=%s iterations=%d messages=%d last_role=%s tool_calls_in_last=%d tools=[%s] last_content="%s" prompt_tokens=%d completion_tokens=%d',
			$model,
			$iteration_count,
			$message_count,
			$last_role,
			$tool_calls_in_last,
			implode( ',', array_slice( $tool_names, 0, 5 ) ),
			str_replace( array( "\n", "\r" ), ' ', $last_content ),
			$prompt_tokens,
			$comp_tokens
		);

		$user_parts = array( 'Nisam uspela da formulisem odgovor.' );
		if ( $iteration_count > 0 && ! empty( $tool_names ) ) {
			$user_parts[] = 'Koristila sam alate (' . implode( ', ', array_slice( $tool_names, 0, 3 ) ) . ') ali LLM nije vratio tekstualni odgovor.';
		} elseif ( 0 === $iteration_count ) {
			$user_parts[] = 'Model nije vratio odgovor. Moguc API problem.';
		} elseif ( $comp_tokens < 5 ) {
			$user_parts[] = 'Model je vratio prazan odgovor (0 tokena). Moguc rate-limit ili timeout.';
		}
		$user_parts[] = 'Pokusaj ponovo ili posalji /reset za novu sesiju.';

		return array(
			'log_line'     => $log_line,
			'user_message' => implode( ' ', $user_parts ),
		);
	}
}
