<?php
/**
 * Normalizes agent-loop tool execution outcomes.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Agent_Tool_Execution_Outcome {

	const DEFAULT_TERMINAL_REPLY = 'Zaustavljam ovaj turn jer je upao u ponavljajuci read-only coding shell ciklus bez izmena.';

	public static function terminal_result( $reply, $partial_results, $terminal_context ) {
		return array(
			'_terminal'         => true,
			'_reply'            => (string) $reply,
			'_partial_results'  => is_array( $partial_results ) ? $partial_results : array(),
			'_terminal_context' => is_array( $terminal_context ) ? $terminal_context : array(),
		);
	}

	public static function workspace_apply_context( $call_name, $decoded_result ) {
		return array(
			'last_tool' => $call_name,
			'guard'     => 'main_coding_workspace_apply_success',
			'reason'    => 'completed_after_workspace_apply',
			'result'    => is_array( $decoded_result ) ? $decoded_result : array(),
		);
	}

	public static function normalize( $tool_result_messages ) {
		$outcome = array(
			'cancelled'        => false,
			'terminal'         => false,
			'reply'            => '',
			'partial_results'  => array(),
			'terminal_context' => array(),
		);

		if ( null === $tool_result_messages ) {
			$outcome['cancelled'] = true;
			return $outcome;
		}

		if ( ! is_array( $tool_result_messages ) ) {
			return $outcome;
		}

		if ( ! empty( $tool_result_messages['_cancelled'] ) ) {
			$outcome['cancelled']       = true;
			$outcome['partial_results'] = isset( $tool_result_messages['_partial_results'] ) ? (array) $tool_result_messages['_partial_results'] : array();
			return $outcome;
		}

		if ( ! empty( $tool_result_messages['_terminal'] ) ) {
			$outcome['terminal']         = true;
			$outcome['reply']            = isset( $tool_result_messages['_reply'] ) ? (string) $tool_result_messages['_reply'] : self::DEFAULT_TERMINAL_REPLY;
			$outcome['partial_results']  = isset( $tool_result_messages['_partial_results'] ) ? (array) $tool_result_messages['_partial_results'] : array();
			$outcome['terminal_context'] = isset( $tool_result_messages['_terminal_context'] ) && is_array( $tool_result_messages['_terminal_context'] ) ? $tool_result_messages['_terminal_context'] : array();
		}

		return $outcome;
	}
}
