<?php
/**
 * Sanitizer for prompt-like text fields.
 *
 * @package Contentosapp_Studio
 */

defined( 'ABSPATH' ) || exit;

class Costudio_Prompt_Sanitizer {
	const MAX_LENGTH = 80000;

	/**
	 * Preserve prompt syntax (Markdown, JSON, placeholders, {{ref:N}}) while
	 * removing control bytes that do not belong in an LLM instruction.
	 */
	public static function sanitize( $raw, int $max_length = self::MAX_LENGTH ): string {
		if ( is_array( $raw ) || is_object( $raw ) ) {
			return '';
		}

		$text = wp_unslash( (string) $raw );
		$text = str_replace( [ "\r\n", "\r" ], "\n", $text );
		$text = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $text );
		$text = trim( $text );

		if ( function_exists( 'mb_strlen' ) && function_exists( 'mb_substr' ) ) {
			return mb_strlen( $text ) > $max_length ? mb_substr( $text, 0, $max_length ) : $text;
		}

		return strlen( $text ) > $max_length ? substr( $text, 0, $max_length ) : $text;
	}
}
