<?php
/**
 * Generated post persistence service.
 *
 * @package SmartyPress_AI_Engine
 */

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

/**
 * Creates WordPress posts from generated content.
 */
class SmartyPress_AI_Content_Generator_Post_Persistence_Service {

	/**
	 * Markdown converter.
	 *
	 * @var SmartyPress_AI_Content_Generator_Markdown_Block_Converter
	 */
	private $converter;

	/**
	 * Structured article block renderer.
	 *
	 * @var SmartyPress_AI_Content_Generator_Article_Block_Renderer
	 */
	private $article_renderer;

	/**
	 * SEO metadata builder.
	 *
	 * @var SmartyPress_AI_Content_Generator_SEO_Generation_Metadata_Service
	 */
	private $seo_metadata;

	/**
	 * SEO plugin metadata writer.
	 *
	 * @var SmartyPress_AI_Content_Generator_SEO_Plugin_Metadata_Writer
	 */
	private $seo_writer;

	/**
	 * Constructor.
	 *
	 * @param SmartyPress_AI_Content_Generator_Markdown_Block_Converter $converter Markdown converter.
	 * @param SmartyPress_AI_Content_Generator_Article_Block_Renderer        $article_renderer Article block renderer.
	 * @param SmartyPress_AI_Content_Generator_SEO_Generation_Metadata_Service|null $seo_metadata SEO metadata service.
	 * @param SmartyPress_AI_Content_Generator_SEO_Plugin_Metadata_Writer|null $seo_writer SEO writer.
	 */
	public function __construct( SmartyPress_AI_Content_Generator_Markdown_Block_Converter $converter, SmartyPress_AI_Content_Generator_Article_Block_Renderer $article_renderer, $seo_metadata = null, $seo_writer = null ) {
		$this->converter        = $converter;
		$this->article_renderer = $article_renderer;
		$this->seo_metadata     = $seo_metadata instanceof SmartyPress_AI_Content_Generator_SEO_Generation_Metadata_Service ? $seo_metadata : new SmartyPress_AI_Content_Generator_SEO_Generation_Metadata_Service();
		$this->seo_writer       = $seo_writer instanceof SmartyPress_AI_Content_Generator_SEO_Plugin_Metadata_Writer ? $seo_writer : new SmartyPress_AI_Content_Generator_SEO_Plugin_Metadata_Writer();
	}

	/**
	 * Create a WordPress post from generated fields.
	 *
	 * @param array $post_data Generated post fields.
	 * @return array Response with post ID or error.
	 */
	public function create_post( $post_data ) {
		$post_data = wp_parse_args(
			$post_data,
			array(
				'post_title'          => '',
				'post_content'        => '',
				'post_excerpt'        => '',
				'post_status'         => 'draft',
				'post_type'           => 'post',
				'categories'          => array(),
				'content_format'      => 'legacy_markdown',
				'post_content_blocks' => array(),
				'seo_metadata'        => array(),
				'seo_keywords'        => array(),
				'product_meta'        => array(),
			)
		);
		$post_data = $this->seo_metadata->normalize_post_data( $post_data );

		if ( empty( $post_data['post_title'] ) || ( empty( $post_data['post_content'] ) && empty( $post_data['post_content_blocks'] ) ) ) {
			return array(
				'success' => false,
				'error'   => __( 'Title and content are required', 'smartypress-ai-engine' ),
			);
		}

		$post_content = $this->prepare_post_content( $post_data );

		if ( '' === trim( $post_content ) ) {
			return array(
				'success' => false,
				'error'   => __( 'Title and content are required', 'smartypress-ai-engine' ),
			);
		}

		$post_id = wp_insert_post(
			array(
				'post_title'   => sanitize_text_field( $post_data['post_title'] ),
				'post_content' => wp_kses_post( $post_content ),
				'post_excerpt' => sanitize_textarea_field( $post_data['post_excerpt'] ),
				'post_status'  => sanitize_text_field( $post_data['post_status'] ),
				'post_type'    => sanitize_text_field( $post_data['post_type'] ),
			),
			true
		);

		if ( is_wp_error( $post_id ) ) {
			return array(
				'success' => false,
				'error'   => $post_id->get_error_message(),
			);
		}

		if ( ! empty( $post_data['categories'] ) && is_array( $post_data['categories'] ) ) {
			wp_set_post_categories( $post_id, $post_data['categories'] );
		}

		$product_defaults = $this->maybe_apply_product_defaults( $post_id, $post_data );
		$seo_result = $this->seo_writer->apply( $post_id, $post_data['seo_metadata'] ?? array() );

		return array(
			'success'          => true,
			'post_id'          => $post_id,
			'edit_url'         => admin_url( 'post.php?action=edit&post=' . $post_id ),
			'view_url'         => get_permalink( $post_id ),
			'seo_metadata'     => $post_data['seo_metadata'] ?? array(),
			'seo_updated'      => $seo_result,
			'product_defaults' => $product_defaults,
		);
	}

	/**
	 * Apply safe WooCommerce defaults for generated draft products.
	 *
	 * @param int   $post_id   Post ID.
	 * @param array $post_data Generated post data.
	 * @return array Applied defaults.
	 */
	private function maybe_apply_product_defaults( $post_id, array $post_data ) {
		$post_id   = absint( $post_id );
		$post_type = sanitize_key( $post_data['post_type'] ?? '' );

		if ( ! $post_id || 'product' !== $post_type || ! post_type_exists( 'product' ) ) {
			return array();
		}

		$applied = array();

		if ( taxonomy_exists( 'product_type' ) ) {
			wp_set_object_terms( $post_id, 'simple', 'product_type', false );
			$applied[] = 'product_type';
		}

		$meta_defaults = array(
			'_stock_status'      => 'instock',
			'_manage_stock'      => 'no',
			'_virtual'           => 'no',
			'_downloadable'      => 'no',
			'_sold_individually' => 'no',
			'_tax_status'        => 'taxable',
			'_visibility'        => 'visible',
			'_regular_price'     => '',
			'_sale_price'        => '',
			'_price'             => '',
		);

		foreach ( $meta_defaults as $meta_key => $meta_value ) {
			update_post_meta( $post_id, $meta_key, $meta_value );
			$applied[] = $meta_key;
		}

		$product_meta = is_array( $post_data['product_meta'] ?? null ) ? $post_data['product_meta'] : array();
		$sku          = sanitize_text_field( $product_meta['sku'] ?? '' );
		$attributes   = sanitize_textarea_field( $product_meta['attributes'] ?? '' );

		if ( '' !== $sku ) {
			update_post_meta( $post_id, '_sku', $sku );
			$applied[] = '_sku';
		}

		if ( '' !== $attributes ) {
			update_post_meta( $post_id, '_smartypress_ai_product_attributes', $attributes );
			$applied[] = '_smartypress_ai_product_attributes';
		}

		if ( function_exists( 'wc_get_product' ) ) {
			$product = wc_get_product( $post_id );
			if ( $product && method_exists( $product, 'save' ) ) {
				$product->save();
				$applied[] = 'wc_product_save';
			}
		}

		return array_values( array_unique( $applied ) );
	}

	/**
	 * Prepare post content for the target editor.
	 *
	 * @param array $post_data Generated post fields.
	 * @return string
	 */
	private function prepare_post_content( $post_data ) {
		$content_format = sanitize_key( $post_data['content_format'] ?? 'legacy_markdown' );
		$output_format  = $this->get_content_output_format( $post_data );

		if ( 'article_blocks' === $content_format || ! empty( $post_data['post_content_blocks'] ) ) {
			$article = is_array( $post_data['post_content_blocks'] ) ? $post_data['post_content_blocks'] : array();

			if ( 'legacy_markdown' === $output_format && ! empty( $post_data['post_content'] ) ) {
				$html = SmartyPress_AI_Prompt_Processor::markdown_to_html( $post_data['post_content'] );

				return $this->converter->html_to_gutenberg_blocks( $html );
			}

			return 'html' === $output_format
				? $this->article_renderer->to_classic_html(
					$article,
					array(
						'plain_lead' => 'product' === sanitize_key( $post_data['post_type'] ?? '' ),
					)
				)
				: $this->article_renderer->to_gutenberg_blocks( $article );
		}

		$html = SmartyPress_AI_Prompt_Processor::markdown_to_html( $post_data['post_content'] );

		return $this->converter->html_to_gutenberg_blocks( $html );
	}

	/**
	 * Determine content output format.
	 *
	 * @param array $post_data Generated post fields.
	 * @return string
	 */
	private function get_content_output_format( $post_data ) {
		$post_type = sanitize_key( $post_data['post_type'] ?? 'post' );
		$format    = 'gutenberg';

		if ( function_exists( 'use_block_editor_for_post_type' ) && ! use_block_editor_for_post_type( $post_type ) ) {
			$format = 'html';
		}

		/**
		 * Filters generated content output format.
		 *
		 * Supported values: gutenberg, html, legacy_markdown.
		 *
		 * @param string $format Output format.
		 * @param array  $post_data Generated post fields.
		 */
		$format = apply_filters( 'smartypress_ai_content_output_format', $format, $post_data );
		$format = sanitize_key( $format );

		return in_array( $format, array( 'gutenberg', 'html', 'legacy_markdown' ), true ) ? $format : 'gutenberg';
	}
}
