<?php
/**
 * Content Cleaner for Context Awareness.
 *
 * @package Replyan_AI
 */

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

class Replyan_AI_Content_Cleaner {

	/**
	 * Cleans the raw content for embedding generation.
	 *
	 * @param string $content The raw content.
	 * @return string The cleaned content.
	 */
	public function clean( string $content ): string {
		// Strip shortcodes
		$content = strip_shortcodes( $content );

		// Remove scripts and styles
		$content = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $content );

		// Convert HTML block tags and line breaks to newlines before stripping tags
		$content = preg_replace( '/<(?:br|\/p|\/div|\/li|\/tr|\/h[1-6])[^>]*>/i', "\n", $content );

		// Strip remaining HTML tags
		$content = wp_strip_all_tags( $content );

		// Decode HTML entities
		$content = html_entity_decode( $content, ENT_QUOTES, 'UTF-8' );

		// Standardize line endings (\r\n and \r -> \n)
		$content = str_replace( array( "\r\n", "\r" ), "\n", $content );

		// Normalize horizontal whitespace (multiple spaces/tabs) without removing newlines
		$content = preg_replace( '/[^\S\r\n]+/', ' ', $content );

		// Trim each individual line
		$lines   = explode( "\n", $content );
		$trimmed = array_map( 'trim', $lines );
		$content = implode( "\n", $trimmed );

		// Normalize multiple consecutive blank lines to at most two newlines
		$content = preg_replace( '/\n{3,}/', "\n\n", $content );

		return trim( $content );
	}
}
