<?php
/**
 * This file is part of the Wisewand WordPress plugin.
 *
 * @package Wisewand
 * @since 1.0.0
 * @license GPL-2.0-or-later
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */
namespace Wisewand\Utils;

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Wisewand\Logging\Logger;
use Wisewand\Utils\Options;

// phpcs:disable WordPress.PHP.DevelopmentFunctions.error_log_error_log -- error_log() is only used within WP_DEBUG conditionals for debugging

class Import_Enhancer {

	private $logger;
	private $options;
	private $rate_limiter;

	public function __construct( Logger $logger, ?Options $options = null, $rate_limiter = null ) {
		$this->logger  = $logger;
		$this->options = $options;

		// If options not provided, create instance (backwards compatibility)
		if ( ! $this->options ) {
			if ( class_exists( 'Wisewand\\Utils\\Options' ) ) {
				$this->options = new Options();
			}
		}
		$this->rate_limiter = $rate_limiter ?? new \Wisewand\Utils\Rate_Limiter( $this->logger );
	}

	/**
	 * Enhanced import workflow that ensures proper media and SEO processing
	 */
	public function enhance_post_import( $post_id, $api_data ) {
		$this->logger->info(
			'Starting enhanced import processing',
			array(
				'post_id'    => $post_id,
				'article_id' => $api_data['id'] ?? 'unknown',
			)
		);

		$warnings = array();

		// Step 1: EXTRACT FAQ FIRST (before Content_Cleaner modifies HTML!)
		// This must run on ORIGINAL content before any cleaning/modification
		$faq_warnings = $this->extract_and_process_faq( $post_id, $api_data );
		$warnings     = array_merge( $warnings, $faq_warnings );

		// Step 2: Process and download all media
		$media_warnings = $this->process_all_media( $post_id, $api_data );
		$warnings       = array_merge( $warnings, $media_warnings );

		// Step 3: Update post content with new media URLs and add audio player
		// NOTE: Content_Cleaner runs here and modifies HTML (including FAQ section)
		$content_warnings = $this->update_content_with_local_media( $post_id, $api_data );
		$warnings         = array_merge( $warnings, $content_warnings );

		// Step 4: Ensure SEO data includes local image URLs
		$seo_warnings = $this->update_seo_with_local_media( $post_id );
		$warnings     = array_merge( $warnings, $seo_warnings );

		// Step 5: Verify WPML integration
		$wpml_warnings = $this->verify_wpml_integration( $post_id, $api_data );
		$warnings      = array_merge( $warnings, $wpml_warnings );

		$this->logger->info(
			'Enhanced import processing completed',
			array(
				'post_id'        => $post_id,
				'warnings_count' => count( $warnings ),
				'warnings'       => $warnings,
			)
		);

		return $warnings;
	}

	private function process_all_media( $post_id, $api_data ) {
		$warnings = array();

		// Get the Media_Manager
		$plugin        = \Wisewand\Core\Plugin::instance();
		$media_manager = $plugin->get_media_manager();

		if ( ! $media_manager ) {
			$warnings[] = 'Media manager not available';
			return $warnings;
		}

		$output = $api_data['output'] ?? $api_data['data']['output'] ?? array();

		// Get post context for AI metadata generation
		$post            = get_post( $post_id );
		$article_title   = $post ? $post->post_title : '';
		$article_content = $post ? $post->post_content : '';

		// Check if AI metadata generation is enabled
		$generate_ai_metadata = $this->should_generate_ai_metadata();

		// Process featured image with AI metadata
		if ( ! empty( $output['cover_image'] ) ) {
			$featured_metadata = array();

			if ( $generate_ai_metadata ) {
				$featured_metadata = $this->generate_image_metadata_with_fallback(
					$article_title,
					$article_content,
					$output['cover_image'],
					'featured',
					1,
					$output
				);
			}

			$result = $media_manager->download_featured_image( $output['cover_image'], $post_id, $featured_metadata );
			if ( is_wp_error( $result ) ) {
				$warnings[] = 'Featured image download failed: ' . $result->get_error_message();
			} else {
				$this->logger->info(
					'Featured image processed',
					array(
						'post_id'         => $post_id,
						'attachment_id'   => $result['attachment_id'],
						'original_url'    => $output['cover_image'],
						'has_ai_metadata' => ! empty( $featured_metadata ),
					)
				);
			}
		}

		// Process cover images (gallery) with AI metadata
		if ( ! empty( $output['cover_images'] ) && is_array( $output['cover_images'] ) ) {
			$gallery_metadata_array = array();

			if ( $generate_ai_metadata ) {
				foreach ( $output['cover_images'] as $index => $image_url ) {
					$gallery_metadata_array[ $index ] = $this->generate_image_metadata_with_fallback(
						$article_title,
						$article_content,
						$image_url,
						'gallery',
						$index + 1,
						$output
					);

					// Rate limiting: Small delay between OpenAI calls
					if ( $index < count( $output['cover_images'] ) - 1 ) {
						$this->rate_limiter->smart_delay( 'openai', 0.5 );
					}
				}
			}

			$gallery_result = $media_manager->download_gallery_images( $output['cover_images'], $post_id, $gallery_metadata_array );
			foreach ( $gallery_result['errors'] as $error ) {
				$warnings[] = 'Gallery image failed: ' . $error['error'];
			}

			if ( ! empty( $gallery_result['successful'] ) ) {
				$this->logger->info(
					'Gallery images processed',
					array(
						'post_id'          => $post_id,
						'images_count'     => count( $gallery_result['successful'] ),
						'with_ai_metadata' => $generate_ai_metadata,
					)
				);
			}
		}

		// Process audio
		if ( ! empty( $output['audio'] ) ) {
			$result = $media_manager->download_audio( $output['audio'], $post_id );
			if ( is_wp_error( $result ) ) {
				$warnings[] = 'Audio download failed: ' . $result->get_error_message();
			} else {
				$this->logger->info(
					'Audio processed',
					array(
						'post_id'       => $post_id,
						'attachment_id' => $result['attachment_id'],
						'original_url'  => $output['audio'],
					)
				);
			}
		}

		return $warnings;
	}

	private function update_content_with_local_media( $post_id, $api_data ) {
		$warnings = array();

		$post = get_post( $post_id );
		if ( ! $post ) {
			$warnings[] = 'Post not found for media URL update';
			return $warnings;
		}

		$plugin        = \Wisewand\Core\Plugin::instance();
		$media_manager = $plugin->get_media_manager();

		if ( ! $media_manager ) {
			$warnings[] = 'Media manager not available for content update';
			return $warnings;
		}

		$original_content = $post->post_content;
		$updated_content  = $original_content;

		// Load Content_Cleaner for content processing
		if ( ! class_exists( 'Wisewand\\Utils\\Content_Cleaner' ) ) {
			$cleaner_file = WISEWAND_PLUGIN_DIR . 'includes/Utils/Content_Cleaner.php';
			if ( file_exists( $cleaner_file ) ) {
				require_once $cleaner_file;
			}
		}

		// Clean content (fix encoded HTML first, then remove H1 if setting enabled)
		if ( class_exists( 'Wisewand\\Utils\\Content_Cleaner' ) ) {
			$updated_content = \Wisewand\Utils\Content_Cleaner::clean_content(
				$updated_content,
				array(
					'fix_encoded_html'       => true,  // Fix &lt;img&gt; tags FIRST
					'remove_h1'              => $this->options ? $this->options->get( 'wisewand_remove_h1_tags', true ) : true,
					'fix_headings'           => false,  // Keep Wisewand's original heading structure (H2 stays H2, H3 stays H3)
					'clean_empty_paragraphs' => true,
					'optimize_images'        => true,
				)
			);

			$this->logger->info(
				'Content cleaned and HTML fixed',
				array(
					'post_id'                       => $post_id,
					'content_length_after_cleaning' => strlen( $updated_content ),
				)
			);
		}

		// Process inline images with AI metadata generation
		$output          = $api_data['output'] ?? $api_data['data']['output'] ?? array();
		$updated_content = $media_manager->process_inline_images(
			$updated_content,
			$post_id,
			$post->post_title,
			$updated_content, // Pass content for AI context
			$output
		);

		// Process inline audio
		$updated_content = $media_manager->process_inline_audio( $updated_content, $post_id );

		// Add audio player if audio was downloaded and setting is enabled
		$audio_url = get_post_meta( $post_id, '_wisewand_audio_url', true );
		if ( ! empty( $audio_url ) ) {
			$plugin         = \Wisewand\Core\Plugin::instance();
			$options        = $plugin->get_options();
			$media_settings = $options->get_media_settings();

			if ( $media_settings['add_audio_player'] && $media_settings['audio_player_position'] !== 'none' ) {
				// Check if audio player doesn't already exist (check for both class names)
				if ( strpos( $updated_content, 'wp-audio-player' ) === false &&
					strpos( $updated_content, 'wisewand-audio-player' ) === false ) {

					if ( class_exists( 'Wisewand\\Utils\\Content_Cleaner' ) ) {
						$audio_id     = get_post_meta( $post_id, '_wisewand_audio_id', true );
						$audio_player = \Wisewand\Utils\Content_Cleaner::generate_audio_player( $audio_url, $audio_id ? (int) $audio_id : null );

						if ( $media_settings['audio_player_position'] === 'top' ) {
							$updated_content = \Wisewand\Utils\Content_Cleaner::prepend_to_content( $updated_content, $audio_player );
						} else {
							$updated_content .= "\n\n" . $audio_player;
						}

						$this->logger->info(
							'Added simple audio player to content',
							array(
								'post_id'   => $post_id,
								'audio_url' => $audio_url,
								'position'  => $media_settings['audio_player_position'],
							)
						);
					}
				}
			}
		}

		// Add RankMath FAQ blocks and remove Wisewand FAQ HTML
		$should_add_faq = get_post_meta( $post_id, '_wisewand_should_add_faq_blocks', true );
		if ( $should_add_faq ) {
			$faq_items = get_post_meta( $post_id, '_wisewand_faq_items', true );

			if ( is_array( $faq_items ) && ! empty( $faq_items ) ) {
				// Remove Wisewand's FAQ HTML (simple <h2>FAQ</h2> format)
				$content_before  = $updated_content;
				$updated_content = $this->remove_faq_section_from_content( $updated_content );

				// Build RankMath FAQ blocks
				$rankmath_blocks = $this->build_rankmath_faq_blocks( $faq_items );

				// Add RankMath blocks to content
				$updated_content .= "\n\n" . $rankmath_blocks;

				if ( WP_DEBUG ) {
					error_log( 'FAQ: ✅ Replaced Wisewand FAQ with RankMath blocks (' . count( $faq_items ) . ' items)' );
				}
			}

			// Cleanup
			delete_post_meta( $post_id, '_wisewand_should_add_faq_blocks' );
			delete_post_meta( $post_id, '_wisewand_faq_items' );
		}

		// Update post if content changed
		if ( $updated_content !== $original_content ) {
			// Preserve audio source tags during update (prevent WordPress from stripping them)
			add_filter( 'wp_kses_allowed_html', array( 'Wisewand\\Utils\\Content_Cleaner', 'allow_audio_kses' ), 10, 2 );

			$update_result = wp_update_post(
				array(
					'ID'           => $post_id,
					'post_content' => $updated_content,
				)
			);

			// Remove filter immediately after update
			remove_filter( 'wp_kses_allowed_html', array( 'Wisewand\\Utils\\Content_Cleaner', 'allow_audio_kses' ), 10 );

			if ( is_wp_error( $update_result ) ) {
				$warnings[] = 'Failed to update post content with enhanced media';
			} else {
				$this->logger->info(
					'Post content enhanced successfully',
					array(
						'post_id'               => $post_id,
						'content_length_before' => strlen( $original_content ),
						'content_length_after'  => strlen( $updated_content ),
						'has_audio_player'      => strpos( $updated_content, 'wisewand-audio-player' ) !== false,
						'h1_tags_removed'       => substr_count( $original_content, '<h1' ) > substr_count( $updated_content, '<h1' ),
						'faq_removed'           => $should_add_faq ? 'yes' : 'no',
					)
				);
			}
		}

		return $warnings;
	}

	private function update_seo_with_local_media( $post_id ) {
		$warnings = array();

		// Get featured image for social sharing
		$featured_image_id = get_post_thumbnail_id( $post_id );
		if ( $featured_image_id ) {
			$local_image_url = wp_get_attachment_image_url( $featured_image_id, 'large' );

			if ( $local_image_url ) {
				// Update SEO data with local image URL
				$seo_data = get_post_meta( $post_id, '_wisewand_seo_data', true );

				if ( $seo_data && is_array( $seo_data ) ) {
					$seo_data['og_image']      = $local_image_url;
					$seo_data['twitter_image'] = $local_image_url;

					update_post_meta( $post_id, '_wisewand_seo_data', $seo_data );

					$this->logger->debug(
						'Updated SEO data with local image URL',
						array(
							'post_id'         => $post_id,
							'local_image_url' => $local_image_url,
						)
					);
				}
			}
		}

		return $warnings;
	}

	private function verify_wpml_integration( $post_id, $api_data ) {
		$warnings = array();

		if ( ! function_exists( 'icl_get_languages' ) ) {
			return $warnings; // WPML not active
		}

		$input = $api_data['input'] ?? $api_data['data']['input'] ?? array();

		if ( empty( $input['lang'] ) ) {
			return $warnings; // No language specified
		}

		$plugin       = \Wisewand\Core\Plugin::instance();
		$wpml_manager = $plugin->get_wpml_manager();

		if ( ! $wpml_manager ) {
			$warnings[] = 'WPML manager not available';
			return $warnings;
		}

		// Verify language was set correctly
		$post_language     = $wpml_manager->get_post_language( $post_id );
		$expected_language = $wpml_manager->determine_wpml_language( $input );

		if ( $post_language !== $expected_language ) {
			$warnings[] = sprintf( 'WPML language mismatch: expected %s, got %s', $expected_language, $post_language );

			// Try to fix it
			if ( $expected_language ) {
				$wpml_manager->set_post_language( $post_id, $expected_language );
				$this->logger->info(
					'Fixed WPML language assignment',
					array(
						'post_id'            => $post_id,
						'corrected_language' => $expected_language,
					)
				);
			}
		}

		return $warnings;
	}

	/**
	 * Test the enhanced import workflow with a specific article
	 */
	public static function test_import_enhancement( $article_id ) {
		if ( ! current_user_can( 'manage_options' ) ) {
			return new \WP_Error( 'insufficient_permissions', 'Insufficient permissions' );
		}

		// Get API client
		$api_key = Wisewand_API_Client::get_stored_api_key();
		if ( empty( $api_key ) ) {
			return new \WP_Error( 'no_api_key', 'No API key configured' );
		}

		$logger     = new Logger();
		$api_client = new Wisewand_API_Client( $api_key, $logger );

		// Fetch article data
		$article_data = $api_client->get_article_output( $article_id );
		if ( is_wp_error( $article_data ) ) {
			return $article_data;
		}

		// Test media processing
		$media_test = self::test_media_processing( $article_data );

		// Test SEO processing
		$seo_test = self::test_seo_processing( $article_data );

		// Test WPML processing
		$wpml_test = self::test_wpml_processing( $article_data );

		return array(
			'article_id'     => $article_id,
			'article_title'  => $article_data['output']['h1'] ?? 'Unknown',
			'media_test'     => $media_test,
			'seo_test'       => $seo_test,
			'wpml_test'      => $wpml_test,
			'overall_status' => 'ready_for_import',
		);
	}

	private static function test_media_processing( $article_data ) {
		$output = $article_data['output'] ?? $article_data['data']['output'] ?? array();

		$media_found = array();

		if ( ! empty( $output['cover_image'] ) ) {
			$media_found['featured_image'] = $output['cover_image'];
		}

		if ( ! empty( $output['cover_images'] ) ) {
			$media_found['gallery_images'] = count( $output['cover_images'] );
		}

		if ( ! empty( $output['audio'] ) ) {
			$media_found['audio'] = $output['audio'];
		}

		// Check for inline media in content
		$content       = $output['content'] ?? '';
		$inline_images = preg_match_all( '/<img[^>]+src=["\']([^"\']+)["\'][^>]*>/i', $content, $matches );
		$inline_audio  = preg_match_all( '/https?:\/\/[^\s<>"]+\.(?:mp3|wav|ogg|m4a)/i', $content, $audio_matches );

		if ( $inline_images > 0 ) {
			$media_found['inline_images'] = $inline_images;
		}

		if ( $inline_audio > 0 ) {
			$media_found['inline_audio'] = $inline_audio;
		}

		return array(
			'media_found'       => $media_found,
			'total_media_items' => count( $media_found ),
			'content_length'    => strlen( $content ),
		);
	}

	private static function test_seo_processing( $article_data ) {
		$output = $article_data['output'] ?? $article_data['data']['output'] ?? array();
		$input  = $article_data['input'] ?? $article_data['data']['input'] ?? array();

		$seo_fields = array();

		if ( ! empty( $output['meta_title'] ) ) {
			$seo_fields['meta_title'] = strlen( $output['meta_title'] );
		}

		if ( ! empty( $output['meta_description'] ) ) {
			$seo_fields['meta_description'] = strlen( $output['meta_description'] );
		}

		if ( ! empty( $input['target_keyword'] ) ) {
			$seo_fields['focus_keyword'] = $input['target_keyword'];
		}

		if ( ! empty( $input['keywords_secondary'] ) ) {
			$seo_fields['secondary_keywords'] = $input['keywords_secondary'];
		}

		if ( ! empty( $output['url'] ) ) {
			$seo_fields['canonical_url'] = $output['url'];
		}

		return array(
			'seo_fields'       => $seo_fields,
			'yoast_active'     => defined( 'WPSEO_VERSION' ),
			'rankmath_active'  => defined( 'RANK_MATH_VERSION' ),
			'total_seo_fields' => count( $seo_fields ),
		);
	}

	private static function test_wpml_processing( $article_data ) {
		$input = $article_data['input'] ?? $article_data['data']['input'] ?? array();

		$wpml_info = array(
			'wpml_active'        => defined( 'ICL_SITEPRESS_VERSION' ),
			'language_specified' => ! empty( $input['lang'] ),
			'country_specified'  => ! empty( $input['country'] ),
		);

		if ( $wpml_info['wpml_active'] ) {
			global $sitepress;
			if ( $sitepress ) {
				$active_languages              = $sitepress->get_active_languages();
				$wpml_info['active_languages'] = array_keys( $active_languages );
				$wpml_info['default_language'] = $sitepress->get_default_language();

				// Check if specified language is active
				$specified_lang                  = $input['lang'] ?? '';
				$wpml_info['language_supported'] = isset( $active_languages[ $specified_lang ] );
			}
		}

		if ( ! empty( $input['translate_of_external_id'] ) ) {
			$wpml_info['is_translation'] = true;
			$wpml_info['translate_of']   = $input['translate_of_external_id'];
		}

		return $wpml_info;
	}

	/**
	 * Extract FAQ from Wisewand API data and set RankMath/Yoast schema
	 * Uses the structured "faq" field from Wisewand API output
	 */
	private function extract_and_process_faq( $post_id, $api_data ) {
		$warnings = array();

		if ( WP_DEBUG ) {
			error_log( 'FAQ: Starting FAQ processing for post ' . $post_id );
		}

		// Get FAQ from Wisewand API output (new structured field)
		$output   = $api_data['output'] ?? $api_data['data']['output'] ?? array();
		$faq_html = $output['faq'] ?? '';

		if ( empty( $faq_html ) ) {
			if ( WP_DEBUG ) {
				error_log( 'FAQ: No FAQ field in API output' );
			}
			$this->logger->debug( 'No FAQ in API output', array( 'post_id' => $post_id ) );
			return $warnings; // No FAQ, no problem
		}

		if ( WP_DEBUG ) {
			error_log( 'FAQ: FAQ field found in API output' );
			error_log( 'FAQ: FAQ HTML length: ' . strlen( $faq_html ) );
		}

		// Parse FAQ HTML to extract Q&A pairs
		$faq_items = $this->parse_faq_html( $faq_html );

		if ( empty( $faq_items ) ) {
			if ( WP_DEBUG ) {
				error_log( 'FAQ: No Q&A pairs found in FAQ HTML' );
			}
			return $warnings;
		}

		if ( WP_DEBUG ) {
			error_log( 'FAQ: ✅ Extracted ' . count( $faq_items ) . ' Q&A pairs' );
			foreach ( $faq_items as $i => $item ) {
				error_log( 'FAQ:   Q' . ( $i + 1 ) . ': ' . substr( $item['question'], 0, 60 ) . '...' );
			}
		}

		// Store FAQ items for later insertion as RankMath blocks
		update_post_meta( $post_id, '_wisewand_faq_items', $faq_items );
		update_post_meta( $post_id, '_wisewand_should_add_faq_blocks', true );

		if ( WP_DEBUG ) {
			error_log( 'FAQ: ✅ FAQ items stored, will add RankMath blocks after content cleaning' );
		}

		return $warnings;
	}

	/**
	 * Parse FAQ HTML from Wisewand API to extract Q&A pairs
	 * Format: <h2>FAQ</h2><h3>Question</h3><p>Answer</p><h3>...</h3><p>...</p>
	 *
	 * @param string $faq_html FAQ HTML from API output
	 * @return array Array of ['question' => '...', 'answer' => '...']
	 */
	private function parse_faq_html( $faq_html ) {
		$faq_items = array();

		// Simple pattern: <h3>Question</h3> followed by <p>Answer</p>
		$pattern = '/<h3[^>]*>(.*?)<\/h3>\s*<p[^>]*>(.*?)<\/p>/is';

		if ( preg_match_all( $pattern, $faq_html, $matches, PREG_SET_ORDER ) ) {
			foreach ( $matches as $match ) {
				$question = trim( wp_strip_all_tags( $match[1] ) );
				$answer   = trim( wp_strip_all_tags( $match[2] ) );

				if ( ! empty( $question ) && ! empty( $answer ) ) {
					$faq_items[] = array(
						'question' => $question,
						'answer'   => $answer,
					);
				}
			}
		}

		return $faq_items;
	}

	/**
	 * Build RankMath FAQ blocks (matches RankMath's exact HTML structure)
	 * RankMath detects FAQ by CSS classes, not Gutenberg block registration
	 */
	private function build_rankmath_faq_blocks( $faq_items ) {
		if ( empty( $faq_items ) ) {
			return '';
		}

		$blocks_html = '';

		foreach ( $faq_items as $item ) {
			if ( empty( $item['question'] ) || empty( $item['answer'] ) ) {
				continue;
			}

			// Sanitize for security but preserve special chars and emojis
			// Use wp_kses_post to allow safe HTML without converting entities
			$question = wp_kses_post( $item['question'] );
			$answer   = wp_kses_post( $item['answer'] );

			// Build exact RankMath block structure
			$blocks_html .= '<div class="wp-block-rank-math-faq-block">';
			$blocks_html .= '<div class="rank-math-faq-item">';
			$blocks_html .= '<h3 class="rank-math-question">' . $question . '</h3>';
			$blocks_html .= '<div class="rank-math-answer">' . $answer . '</div>';
			$blocks_html .= '</div>';
			$blocks_html .= '</div>';
		}

		if ( WP_DEBUG ) {
			error_log( 'FAQ: Built ' . count( $faq_items ) . ' RankMath FAQ blocks (plain HTML)' );
		}

		return $blocks_html;
	}

	/**
	 * Remove Wisewand FAQ section from content
	 * Handles both H2 and H4 (Content_Cleaner converts H2→H4)
	 *
	 * @param string $content Content to clean
	 * @return string Content with Wisewand FAQ section removed
	 */
	private function remove_faq_section_from_content( $content ) {
		$content_before = $content;

		// Pattern 1: H4 FAQ (after Content_Cleaner runs)
		$pattern_h4 = '/<h4[^>]*>\s*FAQ\s*<\/h4>.*?(?=<h4|<div class="wp-block-rank-math|$)/is';
		$content    = preg_replace( $pattern_h4, '', $content );

		if ( $content !== $content_before ) {
			if ( WP_DEBUG ) {
				error_log( 'FAQ: Removed H4 FAQ section' );
			}
		} else {
			// Pattern 2: H2 FAQ (before Content_Cleaner runs)
			$pattern_h2 = '/<h2[^>]*>\s*FAQ\s*<\/h2>.*?(?=<h2|<div class="wp-block-rank-math|$)/is';
			$content    = preg_replace( $pattern_h2, '', $content );

			if ( $content !== $content_before ) {
				if ( WP_DEBUG ) {
					error_log( 'FAQ: Removed H2 FAQ section' );
				}
			}
		}

		// Clean up extra whitespace
		$content = preg_replace( '/\n{3,}/', "\n\n", $content );
		$content = trim( $content );

		return $content;
	}

	/**
	 * Check if AI metadata generation is enabled
	 *
	 * @return bool True if OpenAI metadata generation is enabled and configured
	 */
	private function should_generate_ai_metadata() {
		// Check if feature is enabled in settings
		$plugin  = \Wisewand\Core\Plugin::instance();
		$options = $plugin->get_options();

		if ( ! $options ) {
			return false;
		}

		$generate_metadata = $options->get( 'wisewand_generate_ai_image_metadata', false );

		if ( ! $generate_metadata ) {
			return false;
		}

		// Check if OpenAI is configured
		if ( ! class_exists( 'Wisewand\\Utils\\OpenAI_Client' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/OpenAI_Client.php';
		}

		return \Wisewand\Utils\OpenAI_Client::is_configured();
	}

	/**
	 * Generate image metadata with OpenAI and fallback to meta-title
	 *
	 * @param string $article_title Article title
	 * @param string $article_content Full article content
	 * @param string $image_url Image URL
	 * @param string $position Image position (featured, inline, gallery)
	 * @param int    $index Image index
	 * @param array  $output Article output data (for meta_title fallback)
	 * @return array Metadata array with alt, title, caption, description
	 */
	private function generate_image_metadata_with_fallback( $article_title, $article_content, $image_url, $position, $index, $output ) {
		// Try OpenAI generation first
		if ( ! class_exists( 'Wisewand\\Utils\\OpenAI_Client' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/OpenAI_Client.php';
		}

		$api_key = \Wisewand\Utils\OpenAI_Client::get_stored_api_key();

		if ( empty( $api_key ) ) {
			if ( WP_DEBUG ) {
				error_log( 'AI_METADATA: OpenAI not configured, using fallback' );
			}
			return $this->get_fallback_image_metadata( $article_title, $output );
		}

		$openai_client = new \Wisewand\Utils\OpenAI_Client( $api_key, $this->logger );

		$metadata = $openai_client->generate_image_metadata(
			$article_title,
			$article_content,
			$image_url,
			$position,
			$index
		);

		if ( is_wp_error( $metadata ) ) {
			if ( WP_DEBUG ) {
				error_log( 'AI_METADATA: OpenAI generation failed: ' . $metadata->get_error_message() . ', using fallback' );
			}

			// Fallback to meta-title based metadata
			return $this->get_fallback_image_metadata( $article_title, $output );
		}

		if ( WP_DEBUG ) {
			error_log( 'AI_METADATA: Successfully generated for ' . $position . ' image' );
		}

		return $metadata;
	}

	/**
	 * Get fallback image metadata when OpenAI fails or is disabled
	 *
	 * Uses article meta_title or title as fallback for alt text
	 *
	 * @param string $article_title Article title
	 * @param array  $output Article output data
	 * @return array Metadata array
	 */
	private function get_fallback_image_metadata( $article_title, $output ) {
		// Use meta_title if available (more SEO-optimized), fallback to article title
		$meta_title = $output['meta_title'] ?? $article_title;

		$metadata = array(
			'alt'         => $meta_title,
			'title'       => $meta_title,
			'caption'     => '',
			'description' => '',
		);

		if ( WP_DEBUG ) {
			error_log( 'AI_METADATA: Using fallback metadata with meta_title/title: "' . $meta_title . '"' );
		}

		return $metadata;
	}

}
