<?php
/**
 * Formats admin autonomy run plan previews.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Plan_Preview_Builder {

	public function build( $run ) {
		$run           = is_array( $run ) ? $run : array();
		$plan          = isset( $run['plan'] ) && is_array( $run['plan'] ) ? $run['plan'] : array();
		$actions       = isset( $plan['actions'] ) && is_array( $plan['actions'] ) ? $plan['actions'] : array();
		$preview_lines = array();

		foreach ( array_slice( $actions, 0, 4 ) as $action ) {
			if ( empty( $action['summary'] ) ) {
				continue;
			}
			$preview_lines[] = '- ' . (string) $action['summary'];
		}

		$warnings      = isset( $plan['warnings'] ) && is_array( $plan['warnings'] ) ? array_filter( $plan['warnings'] ) : array();
		$warnings_line = ! empty( $warnings ) ? "\nWarnings: " . implode( ' | ', $warnings ) : '';
		$actions_block = ! empty( $preview_lines ) ? "\n" . implode( "\n", $preview_lines ) : '';

		return sprintf(
			"Run #%d summary.\n%s%s%s\nRollback: %s",
			intval( isset( $run['id'] ) ? $run['id'] : 0 ),
			isset( $plan['summary'] ) ? (string) $plan['summary'] : 'Run plan spreman.',
			$actions_block,
			$warnings_line,
			isset( $plan['rollback_plan'] ) ? (string) $plan['rollback_plan'] : 'Rollback nije deklarisan.'
		);
	}
}
