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

/**
 * Token-saving article summaries passed between pipeline agents.
 */
final class Costudio_Pipeline_Summaries {

	private function __construct() {
	}

	/**
	 * Extracts headings, [IMG:] markers, metadata lines and the full FAQ section
	 * for the visual designer.
	 */
	public static function summarize_article_for_designer( string $text ): string {
		$faq_block = '';
		if (
			preg_match(
				'/(^|\R)(##\s+(?:Perguntas\s+Frequentes|Preguntas\s+Frecuentes|Frequently\s+Asked\s+Questions|FAQ)\b[^\n]*)(.*?)(?=\R##\s|\z)/iu',
				$text,
				$faq_match
			)
		) {
			$faq_block = trim( $faq_match[2] . $faq_match[3] );
		}

		$lines     = explode( "\n", $text );
		$summary   = array();
		$intro_cnt = 0;

		foreach ( $lines as $line ) {
			$trimmed = trim( $line );
			if ( empty( $trimmed ) ) {
				continue;
			}

			if ( 0 === strpos( $trimmed, '#' ) ) {
				$summary[] = $trimmed;
				continue;
			}

			if ( false !== strpos( $trimmed, '[IMG:' ) ) {
				$summary[] = $trimmed;
				continue;
			}

			if ( preg_match( '/^(Título|Meta Description|Slug|SEO Title|Focus Keyword|URL Slug)\s*:/ui', $trimmed ) ) {
				$summary[] = $trimmed;
				continue;
			}

			if ( $intro_cnt < 3 ) {
				$summary[] = $trimmed;
				$intro_cnt++;
			}
		}

		$result = implode( "\n", $summary );

		if ( '' !== $faq_block ) {
			$result .= "\n\n=== FAQ INTEGRAL (use these exact Q&A pairs for the FAQPage schema) ===\n\n"
				. $faq_block;
		}

		$img_list = self::build_image_list_block( $text );
		if ( '' !== $img_list ) {
			$result .= "\n\n=== LISTA CANÓNICA DE IMAGENS INLINE (Obrigatório: um bloco de prompt por linha; o filename deve coincidir exatamente com o texto entre crases) ===\n\n"
				. $img_list;
		}

		return $result;
	}

	public static function build_image_list_block( string $text ): string {
		if (
			! preg_match_all(
				'/\[IMG:\s*([^\|\]]+)\s*\|\s*([^\]]+)\]/',
				$text,
				$matches,
				PREG_SET_ORDER
			)
		) {
			return '';
		}

		$lines = array();
		foreach ( $matches as $m ) {
			$fn  = trim( $m[1] );
			$alt = trim( $m[2] );
			if ( '' === $fn || '' === $alt ) {
				continue;
			}
			$lines[] = '- `' . $fn . '` — ' . $alt;
		}

		if ( array() === $lines ) {
			return '';
		}

		return "[IMAGE_LIST]\n" . implode( "\n", $lines ) . "\n[/IMAGE_LIST]";
	}

	/**
	 * Extracts title, meta, headings, intro and key stats for Agent 06.
	 */
	public static function summarize_article_for_social( string $text ): string {
		$lines      = explode( "\n", $text );
		$summary    = array();
		$intro_cnt  = 0;
		$faq_active = false;
		$faq_items  = 0;

		foreach ( $lines as $line ) {
			$trimmed = trim( $line );
			if ( empty( $trimmed ) ) {
				continue;
			}

			if ( preg_match( '/^(Título|Meta Description|Slug)\s*:/ui', $trimmed ) ) {
				$summary[] = $trimmed;
				continue;
			}

			if ( 0 === strpos( $trimmed, '## ' ) ) {
				$faq_active = ( false !== stripos( $trimmed, 'FAQ' ) || false !== stripos( $trimmed, 'Perguntas' ) );
				$summary[]  = $trimmed;
				continue;
			}

			if ( 0 === strpos( $trimmed, '### ' ) ) {
				$summary[] = $trimmed;
				continue;
			}

			if ( $faq_active && $faq_items < 5 && preg_match( '/^\d+[\.\)]/', $trimmed ) ) {
				$summary[] = $trimmed;
				$faq_items++;
				continue;
			}

			if ( $intro_cnt < 5 ) {
				$summary[] = $trimmed;
				$intro_cnt++;
			}
		}

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

	/**
	 * Extracts PAA, gaps, search intent and LSI table from Agent 01.
	 */
	public static function summarize_discovery( string $text ): string {
		$lines         = explode( "\n", $text );
		$summary       = array();
		$in_section    = false;
		$skip_sections = array( 'top 5 concorrentes', 'concorrentes analisados' );

		foreach ( $lines as $line ) {
			$trimmed = trim( $line );

			if ( preg_match( '/^#{2,3}\s+/', $trimmed ) ) {
				$heading_lower = strtolower( $trimmed );
				$in_section    = true;
				foreach ( $skip_sections as $skip ) {
					if ( false !== strpos( $heading_lower, $skip ) ) {
						$in_section = false;
						break;
					}
				}
			}

			if ( $in_section || empty( $trimmed ) ) {
				$summary[] = $line;
			}
		}

		return trim( implode( "\n", $summary ) );
	}
}
