<?php
/**
 * Content plan summary builder service.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Converts flexible dynamic plans into AI-friendly text summaries.
 */
class SmartyPress_AI_Content_Generator_Plan_Summary_Builder {

	/**
	 * Build readable summary from dynamic plan.
	 *
	 * @param array $plan Dynamic plan.
	 * @return string
	 */
	public function build_dynamic_plan_summary( $plan ) {
		if ( empty( $plan['schema']['fields'] ) || ! is_array( $plan['schema']['fields'] ) ) {
			return wp_json_encode( $plan['data'] ?? array(), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
		}

		$lines = $this->build_dynamic_plan_summary_from_fields(
			$plan['schema']['fields'],
			$plan['data'] ?? array()
		);

		return implode( "\n", array_filter( $lines ) );
	}

	/**
	 * Build summary lines recursively.
	 *
	 * @param array $fields Schema fields.
	 * @param array $data Plan data.
	 * @param int   $depth Nesting depth.
	 * @return array
	 */
	public function build_dynamic_plan_summary_from_fields( $fields, $data, $depth = 0 ) {
		$lines  = array();
		$indent = str_repeat( '  ', $depth );

		foreach ( $fields as $field ) {
			$key   = $field['key'] ?? '';
			$label = $field['label'] ?? $key;
			$type  = $field['type'] ?? 'textarea';
			$value = is_array( $data ) && array_key_exists( $key, $data ) ? $data[ $key ] : null;

			if ( 'group' === $type ) {
				$lines[] = $indent . $label . ':';
				$lines   = array_merge(
					$lines,
					$this->build_dynamic_plan_summary_from_fields(
						$field['fields'] ?? array(),
						is_array( $value ) ? $value : array(),
						$depth + 1
					)
				);
				continue;
			}

			if ( 'repeater' === $type ) {
				$lines[] = $indent . $label . ':';

				if ( is_array( $value ) ) {
					foreach ( $value as $index => $item ) {
						$lines[] = $indent . '- ' . sprintf( 'Элемент %d', $index + 1 );
						$lines   = array_merge(
							$lines,
							$this->build_dynamic_plan_summary_from_fields(
								$field['fields'] ?? array(),
								is_array( $item ) ? $item : array(),
								$depth + 1
							)
						);
					}
				}
				continue;
			}

			if ( 'list' === $type ) {
				$items = is_array( $value ) ? array_filter( array_map( 'strval', $value ) ) : array();
				if ( ! empty( $items ) ) {
					$lines[] = $indent . $label . ': ' . implode( ', ', $items );
				}
				continue;
			}

			if ( is_scalar( $value ) && '' !== trim( (string) $value ) ) {
				$lines[] = $indent . $label . ': ' . trim( (string) $value );
			}
		}

		return $lines;
	}

	/**
	 * Find probable post title in dynamic plan data.
	 *
	 * @param array $plan Dynamic plan.
	 * @return string
	 */
	public function find_dynamic_plan_title( $plan ) {
		$data = $plan['data'] ?? array();

		if ( ! is_array( $data ) ) {
			return '';
		}

		$preferred_keys = array( 'title', 'post_title', 'headline', 'h1', 'heading' );
		$title          = $this->find_value_by_keys( $data, $preferred_keys );

		if ( '' !== $title ) {
			return $title;
		}

		return $this->find_first_scalar_value( $data );
	}

	/**
	 * Collect keywords from dynamic plan data.
	 *
	 * @param array $data Dynamic data.
	 * @return array
	 */
	public function collect_dynamic_plan_keywords( $data ) {
		if ( ! is_array( $data ) ) {
			return array();
		}

		$keywords = array();

		foreach ( $data as $key => $value ) {
			$lower_key = strtolower( (string) $key );

			if ( false !== strpos( $lower_key, 'keyword' ) || false !== strpos( $lower_key, 'ключ' ) ) {
				if ( is_array( $value ) ) {
					foreach ( $value as $item ) {
						if ( is_scalar( $item ) ) {
							$keywords[] = sanitize_text_field( (string) $item );
						}
					}
				} elseif ( is_scalar( $value ) ) {
					$keywords[] = sanitize_text_field( (string) $value );
				}
				continue;
			}

			if ( is_array( $value ) ) {
				$keywords = array_merge( $keywords, $this->collect_dynamic_plan_keywords( $value ) );
			}
		}

		return array_values( array_unique( array_filter( $keywords ) ) );
	}

	/**
	 * Find the first value whose key matches one of preferred keys.
	 *
	 * @param array $data Data tree.
	 * @param array $keys Preferred keys.
	 * @return string
	 */
	private function find_value_by_keys( $data, $keys ) {
		foreach ( $data as $key => $value ) {
			if ( in_array( strtolower( (string) $key ), $keys, true ) && is_scalar( $value ) && '' !== trim( (string) $value ) ) {
				return sanitize_text_field( (string) $value );
			}
		}

		foreach ( $data as $value ) {
			if ( is_array( $value ) ) {
				$found = $this->find_value_by_keys( $value, $keys );

				if ( '' !== $found ) {
					return $found;
				}
			}
		}

		return '';
	}

	/**
	 * Find first scalar value in data tree.
	 *
	 * @param array $data Data tree.
	 * @return string
	 */
	private function find_first_scalar_value( $data ) {
		foreach ( $data as $value ) {
			if ( is_scalar( $value ) && '' !== trim( (string) $value ) ) {
				return sanitize_text_field( (string) $value );
			}

			if ( is_array( $value ) ) {
				$found = $this->find_first_scalar_value( $value );

				if ( '' !== $found ) {
					return $found;
				}
			}
		}

		return '';
	}
}
