<?php

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

/**
 * Removes model-visible control artifacts before text reaches the visitor.
 */
class Niwa_AI_Frontend_Response_Postprocessor {

	public function clean_answer( $answer ) {
		$text = trim( (string) $answer );
		if ( '' === $text ) {
			return '';
		}

		$text = trim( preg_replace( '/\[?\bNO_SEARCH_NEEDED\b\]?/i', '', $text ) );
		$text = trim( preg_replace( '/\[\/?(?:CONVERSATION_CONTEXT|ECOMMERCE_SALES_AGENT|FRONTEND_CUSTOMER_SALES_RULES|AI-HUMANIZER)[^\]]*\]/i', '', $text ) );
		for ( $i = 0; $i < 3; $i++ ) {
			$cleaned = $this->strip_leading_meta_sentence( $text );
			if ( $cleaned === $text ) {
				break;
			}
			$text = trim( $cleaned );
		}

		return $text;
	}

	private function strip_leading_meta_sentence( $text ) {
		$patterns = array(
			'/^\s*(?:I(?:\'ll| will| am going to)|I\x{2019}ll)\s+(?:answer|respond|reply)[^\.\n]{0,180}\.\s*/iu',
			'/^\s*(?:I(?:\'ll| will| am going to)|I\x{2019}ll)\s+(?:answer|respond|reply)[^:\n]{0,180}:\s*/iu',
			'/^\s*(?:The user wants|User wants|Need to|We need to|I need to)[^\.\n]{0,180}\.\s*/iu',
			'/^\s*(?:The response should|Response should|Answer should)[^\.\n]{0,180}\.\s*/iu',
			'/^\s*(?:Odgovori(?:cu|\x{0107}u)|Odgovoricu|Odgovor treba|Treba odgovoriti|Korisnik zeli|Korisnik \x{017E}eli|Korisnik trazi|Korisnik tra\x{017E}i)[^\.!\?\n]{0,180}[\.!\?]\s*/iu',
			'/^\s*(?:Odgovori(?:cu|\x{0107}u)|Odgovoricu|Odgovor treba|Treba odgovoriti|Korisnik zeli|Korisnik \x{017E}eli|Korisnik trazi|Korisnik tra\x{017E}i)[^:\n]{0,180}:\s*/iu',
		);
		foreach ( $patterns as $pattern ) {
			$next = preg_replace( $pattern, '', $text, 1 );
			if ( is_string( $next ) && $next !== $text ) {
				return $next;
			}
		}
		return $text;
	}
}
