<?php
/**
 * Writes generated SEO metadata to supported SEO plugins.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Server-side SEO metadata writer for generated posts.
 */
class SmartyPress_AI_Content_Generator_SEO_Plugin_Metadata_Writer {

	/**
	 * Adapter registry.
	 *
	 * @var SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Registry
	 */
	private $registry;

	/**
	 * Constructor.
	 *
	 * @param SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Registry|null $registry Adapter registry.
	 */
	public function __construct( $registry = null ) {
		$this->registry = $registry instanceof SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Registry ? $registry : new SmartyPress_AI_Content_Generator_SEO_Metadata_Adapter_Registry();
	}

	/**
	 * Apply SEO metadata through available adapters.
	 *
	 * @param int   $post_id Post ID.
	 * @param array $metadata Normalized metadata package.
	 * @return array Applied providers and fields.
	 */
	public function apply( $post_id, $metadata ) {
		$post_id  = absint( $post_id );
		$metadata = is_array( $metadata ) ? $this->sanitize_metadata( $metadata ) : array();
		$applied  = array();

		// The writer is called from internal generation flows, including background queues where no UI user is active.
		if ( ! $post_id || empty( $metadata ) ) {
			return $applied;
		}

		$metadata = apply_filters( 'smartypress_ai_seo_metadata_before_write', $metadata, $post_id );
		$metadata = is_array( $metadata ) ? $metadata : array();
		$metadata = $this->sanitize_metadata( $metadata );

		foreach ( $this->registry->get_adapters( $metadata ) as $adapter ) {
			$name = sanitize_key( $adapter->get_name() );

			if ( false === apply_filters( 'smartypress_ai_seo_metadata_adapter_enabled', true, $name, $post_id, $metadata ) ) {
				continue;
			}

			$updated = $adapter->apply( $post_id, $metadata );
			if ( ! empty( $updated ) ) {
				$applied[ $name ] = $updated;
			}
		}

		update_post_meta( $post_id, '_smartypress_ai_focus_keywords', implode( ', ', $metadata['focus_keywords'] ?? array() ) );
		update_post_meta( $post_id, '_smartypress_ai_seo_metadata', $metadata );

		return array_filter( $applied );
	}

	/**
	 * Sanitize normalized metadata.
	 *
	 * @param array $metadata Metadata.
	 * @return array
	 */
	private function sanitize_metadata( $metadata ) {
		$keywords = $this->sanitize_keywords( $metadata['focus_keywords'] ?? array() );
		$primary  = sanitize_text_field( $metadata['primary_keyword'] ?? ( $keywords[0] ?? '' ) );

		if ( '' !== $primary && empty( $keywords ) ) {
			$keywords[] = $primary;
		}

		return array(
			'seo_title'        => sanitize_text_field( $metadata['seo_title'] ?? '' ),
			'meta_description' => sanitize_textarea_field( $metadata['meta_description'] ?? '' ),
			'slug'             => sanitize_title( $metadata['slug'] ?? '' ),
			'focus_keywords'   => array_values( array_slice( $keywords, 0, 5 ) ),
			'primary_keyword'  => $primary,
			'secondary_keywords' => array_values( array_slice( $keywords, 1, 4 ) ),
		);
	}

	/**
	 * Sanitize keywords.
	 *
	 * @param string|array $keywords Keywords.
	 * @return array
	 */
	private function sanitize_keywords( $keywords ) {
		if ( is_string( $keywords ) ) {
			$keywords = preg_split( '/\r\n|\r|\n|,/', $keywords );
		}

		if ( ! is_array( $keywords ) ) {
			return array();
		}

		$items = array();
		foreach ( $keywords as $keyword ) {
			if ( is_scalar( $keyword ) ) {
				$value = trim( preg_replace( '/\s+/u', ' ', sanitize_text_field( (string) $keyword ) ) );
				if ( '' !== $value ) {
					$items[] = $value;
				}
			}
		}

		return array_values( array_unique( $items ) );
	}
}
