<?php
/**
 * Builds workspace-apply terminal finalization payloads.
 *
 * @package Niwa_AI
 */

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

class Niwa_AI_Agent_Workspace_Apply_Finalizer {

	public static function should_suppress_reply( $context ) {
		$context    = is_array( $context ) ? $context : array();
		$session_id = isset( $context['session_id'] ) ? (string) $context['session_id'] : '';
		$channel    = isset( $context['channel'] ) ? self::sanitize_channel( (string) $context['channel'] ) : '';

		return 'telegram' === $channel
			|| '' !== ( isset( $context['chat_id'] ) ? trim( (string) $context['chat_id'] ) : '' )
			|| 0 === strpos( $session_id, 'admin-telegram-' );
	}

	public static function should_finalize_with_llm( $terminal_context, $context ) {
		if ( ! is_array( $terminal_context ) ) {
			return false;
		}

		$guard = isset( $terminal_context['guard'] ) ? (string) $terminal_context['guard'] : '';
		if ( 'main_coding_workspace_apply_success' !== $guard ) {
			return false;
		}

		return self::should_suppress_reply( $context );
	}

	public static function no_tool_api_options( $api_options ) {
		$api_options = is_array( $api_options ) ? $api_options : array();
		unset( $api_options['tools'] );
		$api_options['tool_choice'] = 'none';
		return $api_options;
	}

	public static function llm_summary_prompt( $terminal_context, $context = array() ) {
		$result       = isset( $terminal_context['result'] ) && is_array( $terminal_context['result'] ) ? $terminal_context['result'] : array();
		$operation_id = isset( $result['operation_id'] ) ? trim( (string) $result['operation_id'] ) : '';
		$applied      = isset( $result['applied'] ) && is_array( $result['applied'] ) ? count( $result['applied'] ) : 0;
		$watchdog     = isset( $result['watchdog'] ) && is_array( $result['watchdog'] ) ? $result['watchdog'] : array();
		$health       = ! empty( $watchdog['skipped'] )
			? 'health check je preskočen'
			: ( ! empty( $watchdog['success'] ) ? 'health check je prošao' : 'health check nije prijavljen' );

		$lines = array(
			'[RUNTIME FINALIZATION]',
			'The coding workspace apply has already succeeded. Do not call tools. Do not suggest more checks unless the tool result shows a blocker.',
			'Write the final answer naturally in Serbian, in Niwa voice, as a short human completion message for the current admin user.',
			'Do not print raw JSON. Do not sound like a status template. Mention only useful concrete facts from the applied result.',
			'Applied files: ' . $applied,
			'Verification: ' . $health,
		);

		if ( '' !== $operation_id ) {
			$lines[] = 'Operation id, only mention if useful: ' . $operation_id;
		}

		if ( ! empty( $result['applied'] ) && is_array( $result['applied'] ) ) {
			$paths = array();
			foreach ( $result['applied'] as $item ) {
				if ( is_array( $item ) && ! empty( $item['path'] ) ) {
					$paths[] = (string) $item['path'];
				} elseif ( is_string( $item ) ) {
					$paths[] = $item;
				}
				if ( count( $paths ) >= 6 ) {
					break;
				}
			}
			if ( ! empty( $paths ) ) {
				$lines[] = 'Changed paths: ' . implode( ', ', $paths );
			}
		}

		return implode( "\n", $lines );
	}

	public static function terminal_reply( $decoded, $context = array() ) {
		$decoded      = is_array( $decoded ) ? $decoded : array();
		$operation_id = isset( $decoded['operation_id'] ) ? trim( (string) $decoded['operation_id'] ) : '';
		$applied      = isset( $decoded['applied'] ) && is_array( $decoded['applied'] ) ? count( $decoded['applied'] ) : 0;
		$watchdog     = isset( $decoded['watchdog'] ) && is_array( $decoded['watchdog'] ) ? $decoded['watchdog'] : array();
		$health       = ! empty( $watchdog['skipped'] ) ? 'health check skipped' : 'health check passed';

		if ( self::should_suppress_reply( $context ) ) {
			$parts = array( 'Gotovo, primenila sam izmene' );
			if ( 1 === $applied ) {
				$parts[] = 'ažuriran je 1 fajl';
			} elseif ( $applied > 1 ) {
				$parts[] = 'ažurirano je ' . $applied . ' fajlova';
			}
			$parts[] = ! empty( $watchdog['skipped'] ) ? 'provera sajta je preskočena' : 'provera sajta je prošla';

			return implode( '; ', $parts ) . '.';
		}

		$parts = array( 'Workspace apply succeeded' );

		if ( '' !== $operation_id ) {
			$parts[] = 'operation `' . $operation_id . '`';
		}
		if ( $applied > 0 ) {
			$parts[] = $applied . ' file' . ( 1 === $applied ? '' : 's' ) . ' applied';
		}
		$parts[] = $health;

		return implode( '; ', $parts ) . '.';
	}

	private static function sanitize_channel( $channel ) {
		if ( function_exists( 'sanitize_key' ) ) {
			return sanitize_key( $channel );
		}

		return strtolower( preg_replace( '/[^a-z0-9_\-]/', '', (string) $channel ) );
	}
}
