<?php
/**
 * Outgoing founder/Telegram reply formatting helpers.
 *
 * @package Niwa_AI
 */

defined( 'ABSPATH' ) || exit;

class Niwa_AI_Admin_Autonomy_Outgoing_Reply_Formatter {
	/** @var object|null */
	private $chat_agent;

	public function __construct( $chat_agent = null ) {
		$this->chat_agent = $chat_agent;
	}

	public function set_chat_agent( $chat_agent ) {
		$this->chat_agent = $chat_agent;
	}

	public function normalize( $reply ) {
		$reply = (string) $reply;
		if ( '' === trim( $reply ) ) {
			return $reply;
		}

		if ( class_exists( 'Niwa_AI_Admin_Autonomy_Delivery_Envelope_Normalizer' ) ) {
			$envelope = Niwa_AI_Admin_Autonomy_Delivery_Envelope_Normalizer::normalize( $reply );
			if ( empty( $envelope['send'] ) ) {
				return '';
			}
			$reply = isset( $envelope['message'] ) ? (string) $envelope['message'] : '';
		}

		if ( $this->chat_agent && method_exists( $this->chat_agent, 'normalize_founder_reply_text' ) ) {
			$reply = (string) $this->chat_agent->normalize_founder_reply_text( $reply );
		}

		return $this->strip_raw_tool_markup( $reply );
	}

	public function strip_raw_tool_markup( $reply ) {
		$reply = (string) $reply;
		if ( '' === trim( $reply ) || false === strpos( $reply, '<' ) ) {
			return $reply;
		}

		$original = $reply;
		$reply    = preg_replace( '/<tool_call\b[^>]*>.*?<\/tool_call>/is', '', $reply );
		$reply    = preg_replace( '/<arguments\b[^>]*>.*?<\/arguments>/is', '', (string) $reply );
		$reply    = preg_replace( '/<([a-z][a-z0-9_]*_[a-z0-9_]*)\b[^>]*>.*?<\/\1>/is', '', (string) $reply );
		$reply    = preg_replace( '/<([a-z][a-z0-9_]*_[a-z0-9_]*)\b[^>]*\/>/is', '', (string) $reply );
		$reply    = trim( preg_replace( "/\n{3,}/", "\n\n", (string) $reply ) );

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

		if ( $original !== $reply ) {
			return 'Interni alatni poziv nije smeo da se prikaze kao poruka. Pokusavam ponovo kroz runtime umesto raw tool output-a.';
		}

		return '';
	}

	public function consume_quote_current_directive( $text ) {
		$text = (string) $text;
		if ( '' === trim( $text ) ) {
			return array(
				'text'          => $text,
				'quote_current' => false,
			);
		}

		$quote = false;
		$clean = preg_replace( '/^\s*\[(?:quote_current|quote-current|quote)\]\s*/i', '', $text, 1, $count );
		if ( $count > 0 && is_string( $clean ) ) {
			$quote = true;
			$text  = $clean;
		}

		return array(
			'text'          => $text,
			'quote_current' => $quote,
		);
	}

	public function extract_callback_command( $callback_data ) {
		$callback_data = trim( (string) $callback_data );
		if ( '' === $callback_data || 0 !== strpos( $callback_data, 'niwa:' ) ) {
			return '';
		}

		return preg_replace( '/[^a-z_]/', '', strtolower( (string) substr( $callback_data, 5 ) ) );
	}
}
