<?php
defined( 'ABSPATH' ) || exit;

/**
 * Pure content cleanup helpers used before previewing or publishing posts.
 */
final class Costudio_Publisher_Content_Normalizer {

	private function __construct() {
	}

	/**
	 * Remove LLM editorial disclaimers ("Nota:", placeholders/CMS, etc.) before
	 * reference rendering so tokens are not expanded into stray HTML.
	 */
	public static function strip_editorial_disclaimers( string $content ): string {
		$parts = preg_split( '/\n{2,}/', $content );
		if ( false === $parts ) {
			return $content;
		}

		$keep = array();
		foreach ( $parts as $para ) {
			$t = trim( $para );
			if ( '' === $t ) {
				$keep[] = $para;
				continue;
			}

			$unwrapped = $t;
			$unwrapped = preg_replace( '/^(\*{1,2}|_{1,2})+/u', '', $unwrapped );
			$unwrapped = preg_replace( '/(\*{1,2}|_{1,2})+$/u', '', $unwrapped );
			$unwrapped = trim( $unwrapped );

			if ( preg_match( '/^(Nota|Note|Aviso)\s*:/iu', $unwrapped ) ) {
				continue;
			}

			$low = mb_strtolower( $t, 'UTF-8' );
			if (
				( preg_match( '/(foi\s+gerado\s+com\s+base|gerado\s+com\s+base)/iu', $low )
					&& preg_match( '/(diretrizes\s+do\s+prompt|diretrizes|prompt)/iu', $low ) )
				|| ( preg_match( '/placeholders?/iu', $low ) && preg_match( '/\bcms\b|wordpress/iu', $low ) )
				|| ( preg_match( '/formata[cç][aã]o\s+final/iu', $low ) && preg_match( '/\bcms\b/iu', $low ) )
			) {
				continue;
			}

			$keep[] = $para;
		}

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

	/**
	 * Mix accent with white (10/90), same rule as Costudio_Pipeline::get_soft_color().
	 */
	public static function soft_background_hex( string $hex ): string {
		$hex = ltrim( $hex, '#' );
		if ( 3 === strlen( $hex ) ) {
			$hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
		}
		if ( strlen( $hex ) < 6 || ! ctype_xdigit( substr( $hex, 0, 6 ) ) ) {
			return '#eff6ff';
		}
		$r = hexdec( substr( $hex, 0, 2 ) );
		$g = hexdec( substr( $hex, 2, 2 ) );
		$b = hexdec( substr( $hex, 4, 2 ) );
		$r = (int) round( $r * 0.10 + 255 * 0.90 );
		$g = (int) round( $g * 0.10 + 255 * 0.90 );
		$b = (int) round( $b * 0.10 + 255 * 0.90 );

		return sprintf( '#%02x%02x%02x', $r, $g, $b );
	}

	public static function strip_division_markers( string $content ): string {
		$patterns = array(
			'/^---\s*[^\n]*DIVISÃO DE REDAÇÃO[^\n]*---\s*$/imu',
			'/^---\s*[^\n]*FIM DA PARTE\s*\d[^\n]*---\s*$/imu',
			'/^.*DIVISÃO DE REDAÇÃO.*$/imu',
			'/^.*FIM DA PARTE\s*1.*$/imu',
		);
		foreach ( $patterns as $p ) {
			$content = preg_replace( $p, '', $content );
		}
		return preg_replace( "/\n{3,}/", "\n\n", trim( $content ) );
	}

	/**
	 * Remove a duplicate article title that appears as the first markdown heading.
	 */
	public static function strip_leading_h1( string $content ): string {
		$content = preg_replace( '/^\s*#\s+[^\n]+\n?/u', '', $content, 1 );
		$content = preg_replace( '/^\s*##\s+[^\n]+\n?/u', '', $content, 1 );

		return $content;
	}

	public static function convert_callouts( string $markdown ): string {
		return preg_replace_callback(
			'/(?:^|\n)((?:> [^\n]*\n?)+)/m',
			static function ( array $m ) {
				$block = $m[1];
				if ( ! preg_match( '/^> \[!([A-Z]+)\]/m', $block, $t ) ) {
					return $m[0];
				}
				$type  = strtolower( $t[1] );
				$inner = preg_replace( '/^> ?/m', '', trim( $block ) );
				$inner = preg_replace( '/^\[![A-Z]+\]\n?/m', '', $inner );
				$inner = trim( $inner );

				$parsedown = new \Costudio_Vendor\Markdown();
				$parsedown->setSafeMode( false );
				$inner_html = $parsedown->text( $inner );

				$cls = esc_attr( "callout callout-{$type}" );
				return "\n<!-- wp:group {\"className\":\"{$cls}\"} -->\n"
					. "<div class=\"wp-block-group {$cls}\">\n{$inner_html}\n</div>\n"
					. "<!-- /wp:group -->\n";
			},
			$markdown
		);
	}

	public static function sanitize_placeholder_urls( string $content ): string {
		$content = preg_replace( '/^\d+\.\s.*?\[URL[^\]]*\].*$/mu', '', $content );
		$content = preg_replace( '/\[([^\]]+)\]\(URL[^)]*\)/u', '$1', $content );
		return preg_replace( "/\n{3,}/", "\n\n", $content );
	}
}
