<?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 WP_Error;

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

/**
 * Content Importer Utility
 *
 * Centralized import logic for Wisewand content
 * Used by both manual imports (Articles Page) and automated imports (CRON)
 *
 * This ensures consistent import behavior across all entry points
 * and prevents drift between manual and automated import logic.
 *
 * @package Wisewand
 */

class Content_Importer {

	/**
	 * Transform Wisewand API data to Content Manager format
	 *
	 * This is the PROVEN transformation function from Wisewand_Articles_Page
	 * that handles RankMath, WPML, featured images, and all WordPress integrations.
	 *
	 * @param array  $api_data Raw API response from get_content_output()
	 * @param string $content_type Content type: 'articles', 'categorypages', 'productpages'
	 * @param array  $options Optional. Import options (author_id, categories, etc.)
	 * @return array Transformed data ready for Content_Manager->process_content()
	 */
	public static function transform_api_data( $api_data, $content_type = 'articles', $options = array() ) {


		// Initialize import data structure
		$import_data = array(
			'external_id'         => $api_data['id'] ?? uniqid( 'wisewand_' ),
			'content_type_source' => $content_type,
		);



		// Set WordPress post type based on content type
		switch ( $content_type ) {
			case 'categorypages':
				$import_data['post_type'] = 'page';
				break;
			case 'productpages':
				$import_data['post_type'] = 'product';
				if ( ! post_type_exists( 'product' ) ) {
					$import_data['post_type'] = 'page';
				}
				break;
			case 'articles':
			default:
				$import_data['post_type'] = 'post';
				break;
		}



		// Extract input data - check multiple possible locations
		$input = null;
		if ( isset( $api_data['data']['input'] ) ) {
			$input = $api_data['data']['input'];
		} elseif ( isset( $api_data['input'] ) ) {
			$input = $api_data['input'];
		}


		if ( $input ) {
			$import_data['lang']    = $input['lang'] ?? 'fr';
			$import_data['country'] = $input['country'] ?? 'fr';



			// Handle translation linking (WPML)
			if ( ! empty( $input['translate_of_external_id'] ) ) {
				$import_data['translate_of_external_id'] = $input['translate_of_external_id'];

			}

			// Store original input for reference
			$import_data['input'] = $input;
		}

		// Extract output data - check multiple possible locations
		$output = null;
		if ( isset( $api_data['data']['output'] ) ) {
			$output = $api_data['data']['output'];
		} elseif ( isset( $api_data['output'] ) ) {
			$output = $api_data['output'];
		}

		if ( $output ) {




			// CRITICAL: Title extraction - h1 FIRST, then title
			// This is why manual import works and CRON doesn't!
			$import_data['title'] = $output['h1'] ?? $output['title'] ?? '';



			// Content and excerpt
			$import_data['content'] = $output['content'] ?? '';
			$import_data['excerpt'] = $output['meta_description'] ?? '';

			// Explicitly extract slug from Wisewand URL for SEO optimization
			if ( ! empty( $output['url'] ) ) {
				$parsed_url = wp_parse_url( $output['url'] );
				if ( isset( $parsed_url['path'] ) ) {
					$path = trim( $parsed_url['path'], '/' );
					if ( ! empty( $path ) ) {
						$import_data['post_name'] = sanitize_title( $path );

					}
				}
			}



			// SEO data mapping for RankMath/Yoast
			$import_data['seo'] = array(
				'title'               => ! empty( $output['meta_title'] ) ? $output['meta_title'] : ( $output['h1'] ?? $output['title'] ?? '' ),
				'description'         => ! empty( $output['meta_description'] ) ? $output['meta_description'] : ( $output['excerpt'] ?? wp_trim_words( $output['content'] ?? '', 25 ) ),
				'canonical_url'       => $output['url'] ?? '',
				'focus_keyword'       => ! empty( $output['focus_keyword'] ) ? $output['focus_keyword'] : ( ! empty( $input['target_keyword'] ) ? trim( $input['target_keyword'] ) : '' ),
				'og_title'            => ! empty( $output['meta_title'] ) ? $output['meta_title'] : ( $output['h1'] ?? $output['title'] ?? '' ),
				'og_description'      => ! empty( $output['meta_description'] ) ? $output['meta_description'] : ( $output['excerpt'] ?? wp_trim_words( $output['content'] ?? '', 25 ) ),
				'twitter_title'       => ! empty( $output['meta_title'] ) ? $output['meta_title'] : ( $output['h1'] ?? $output['title'] ?? '' ),
				'twitter_description' => ! empty( $output['meta_description'] ) ? $output['meta_description'] : ( $output['excerpt'] ?? wp_trim_words( $output['content'] ?? '', 25 ) ),
			);



			// Store secondary keywords separately (don't mix with focus keyword for SEO)
			if ( ! empty( $input['keywords_secondary'] ) ) {
				$import_data['secondary_keywords'] = $input['keywords_secondary'];
			}

			// Media - Featured image with social sharing integration
			if ( ! empty( $output['cover_image'] ) ) {
				$import_data['featured_image_url'] = $output['cover_image'];
				// Also set for Open Graph and Twitter
				$import_data['seo']['og_image']      = $output['cover_image'];
				$import_data['seo']['twitter_image'] = $output['cover_image'];

			}

			// Multiple cover images (if available)
			if ( ! empty( $output['cover_images'] ) && is_array( $output['cover_images'] ) ) {
				$import_data['cover_images'] = $output['cover_images'];

			}

			// Audio content
			if ( ! empty( $output['audio'] ) ) {
				$import_data['audio'] = $output['audio'];

			}

			// WordPress publishing data from Wisewand (if configured during generation)
			if ( isset( $output['publishwordpress_status'] ) ) {
				$import_data['post_status'] = $output['publishwordpress_status'];

			}

			// CRITICAL FIX: Priority cascade for category assignment
			// Priority 1: RSS feed target_categories (user's explicit choice)
			// Priority 2: API publishwordpress_category (Wisewand's suggestion)
			// Priority 3: Will fallback to default_category in Content_Manager

			// Check if RSS feed provided explicit categories (HIGHEST PRIORITY)
			if ( isset( $options['categories'] ) && ! empty( $options['categories'] ) ) {
				// Use RSS feed target categories - this is user's explicit choice
				$import_data['categories'] = $options['categories'];


			} elseif ( isset( $output['publishwordpress_category'] ) && $output['publishwordpress_category'] > 0 ) {
				// Fallback to API category if no RSS feed categories specified
				$import_data['categories'] = array( $output['publishwordpress_category'] );


			} elseif ( isset( $output['publishwordpress_category'] ) && $output['publishwordpress_category'] === -2 ) {
				// Auto-category assignment requested
				$import_data['auto_assign_category'] = true;


			}

			if ( isset( $output['publishwordpress_author'] ) && $output['publishwordpress_author'] > 0 ) {
				$import_data['author_id'] = $output['publishwordpress_author'];

			}

			// Handle scheduled publishing
			if ( isset( $output['publishwordpress_date'] ) ) {
				$import_data['post_date'] = $output['publishwordpress_date'];

			}

			// Store full output for reference (Content Manager may need it)
			$import_data['output'] = $output;
		}

		// Additional top-level fields (fallback extraction)
		if ( isset( $api_data['cover_image'] ) && empty( $import_data['featured_image_url'] ) ) {
			$import_data['featured_image_url'] = $api_data['cover_image'];

		}

		if ( isset( $api_data['title'] ) && empty( $import_data['title'] ) ) {
			$import_data['title'] = $api_data['title'];

		}



		return $import_data;
	}

	/**
	 * Complete import workflow
	 *
	 * Fetches content from Wisewand, transforms it, and imports to WordPress
	 * using the proven Content_Manager logic.
	 *
	 * @param string              $article_id Wisewand article/content ID
	 * @param string              $content_type Content type: 'articles', 'categorypages', 'productpages'
	 * @param array               $options Import options (author_id, categories, post_status, etc.)
	 * @param Wisewand_API_Client $api_client Optional API client (will create if not provided)
	 * @param Content_Manager     $content_manager Optional Content Manager (will get from Plugin if not provided)
	 * @return array|WP_Error Import result with post_id or category_id
	 */
	public static function import_content( $article_id, $content_type = 'articles', $options = array(), $api_client = null, $content_manager = null ) {


		// Get API client if not provided
		if ( ! $api_client ) {


			$api_key = Wisewand_API_Client::get_stored_api_key();
			if ( ! $api_key ) {

				return new WP_Error( 'no_api_key', __( 'Wisewand API key not configured', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}

			$api_client = new Wisewand_API_Client( $api_key );

		}

		// Get Content Manager if not provided
		if ( ! $content_manager ) {


			$plugin = \Wisewand\Core\Plugin::instance();



			$content_manager = $plugin->get_content_manager();

			if ( ! $content_manager ) {

				return new WP_Error( 'no_content_manager', __( 'Content Manager not available', 'wisewand-ai-content-writer-seo-content-generator' ) );
			}


		} else {

		}

		// For discoverarticles, verify output exists before attempting import
		if ( $content_type === 'discoverarticles' ) {




			// OPTIMIZATION: Try to get cached last_output_id first to avoid API call
			$cached_output_id = null;
			$plugin           = \Wisewand\Core\Plugin::instance();



			if ( $plugin && method_exists( $plugin, 'get_rss_article_manager' ) ) {
				// Get article manager from plugin
				$article_manager = $plugin->get_rss_article_manager();



				if ( $article_manager && method_exists( $article_manager, 'get_cached_output_id' ) ) {
					$cached_output_id = $article_manager->get_cached_output_id( $article_id );


				}
			}

			// Only make API call if no cached output_id available
			if ( ! $cached_output_id ) {


				// Check if output exists using the API helper method
				$has_output = $api_client->discoverarticle_has_output( $article_id );

				if ( is_wp_error( $has_output ) ) {
					// Check if this is a 404 (article deleted from Wisewand)
					if ( $has_output->get_error_code() === 'wisewand_resource_not_found' ) {
						$error_data = $has_output->get_error_data();



						return new \WP_Error(
							'discoverarticle_deleted',
							__( 'This discoverarticle no longer exists in Wisewand. It may have been deleted or expired.', 'wisewand-ai-content-writer-seo-content-generator' ),
							array(
								'article_id'    => sanitize_text_field( $article_id ),
								'content_type'  => sanitize_text_field( $content_type ),
								'status_code'   => $error_data['status_code'] ?? 404,
								'permanent'     => true,  // Signal this is not retryable
								'user_message'  => __( 'The article is no longer available in Wisewand. You may need to discover new articles from the RSS feed.', 'wisewand-ai-content-writer-seo-content-generator' ),
							)
						);
					}

					// Other errors (network, API down, etc.) - propagate normally

					return $has_output;
				}

				if ( ! $has_output ) {
					$error_message = __( 'Discoverarticle has no generated output yet. It must be generated in Wisewand before importing.', 'wisewand-ai-content-writer-seo-content-generator' );



					return new \WP_Error(
						'no_output_available',
						$error_message,
						array(
							'article_id'   => sanitize_text_field( $article_id ),
							'content_type' => sanitize_text_field( $content_type ),
							'suggestion'   => __( 'Generate the article in Wisewand or use the run_discoverarticle_generation() API method first.', 'wisewand-ai-content-writer-seo-content-generator' ),
						)
					);
				}



			}
		}

		// Fetch content from Wisewand API

		$api_data = $api_client->get_content_output( $article_id, $content_type );

		if ( is_wp_error( $api_data ) ) {

			return $api_data;
		}



		// Transform data using proven function

		$import_data = self::transform_api_data( $api_data, $content_type, $options );



		// Apply options (override transformation defaults with user/entry preferences)
		// NOTE: Categories are now handled in transform_api_data() with proper priority cascade
		if ( ! empty( $options['author_id'] ) ) {
			$import_data['author_id'] = $options['author_id'];

		}

		if ( ! empty( $options['post_status'] ) ) {
			$import_data['post_status'] = $options['post_status'];

		}

		// WPML: Language override (supports both direct override and target_language from RSS feeds)
		if ( ! empty( $options['wpml_language_override'] ) ) {
			$import_data['wpml_language_override'] = $options['wpml_language_override'];

		} elseif ( ! empty( $options['target_language'] ) ) {
			$import_data['wpml_language_override'] = $options['target_language'];

		}

		if ( ! empty( $options['target_post_type'] ) ) {
			$import_data['target_post_type'] = $options['target_post_type'];

		}

		if ( ! empty( $options['post_date'] ) ) {
			$import_data['post_date'] = $options['post_date'];

		}

		// v1.4.0: Pass AI category matching flag to Content Manager
		// CRITICAL FIX: This flag was being lost in transit causing AI matching to never work
		if ( isset( $options['use_ai_category_matching'] ) ) {
			$import_data['use_ai_category_matching'] = (bool) $options['use_ai_category_matching'];

		}





		$result = $content_manager->process_content( $import_data );



		if ( is_wp_error( $result ) ) {

			return $result;
		}



		// Add actual WordPress post_status to result for imported status determination
		if ( isset( $result['post_id'] ) ) {
			$post = get_post( $result['post_id'] );
			if ( $post ) {
				$result['post_status'] = $post->post_status;

			}
		}

		return $result;
	}

	/**
	 * Verify import completed successfully
	 *
	 * Checks that the imported post/category:
	 * - Actually exists in WordPress
	 * - Has all expected data
	 * - Has proper SEO metadata
	 * - Has WPML language set (if applicable)
	 *
	 * @param array|WP_Error $result Import result from Content_Manager
	 * @param string         $article_id Wisewand article ID (for logging)
	 * @return array Verification result with success flag and warnings/errors
	 */
	public static function verify_import( $result, $article_id ) {


		$verification = array(
			'success'  => true,
			'warnings' => array(),
			'errors'   => array(),
		);

		// Check for WP_Error
		if ( is_wp_error( $result ) ) {
			$verification['success']  = false;
			$verification['errors'][] = 'Import returned WP_Error: ' . $result->get_error_message();

			return $verification;
		}

		// Check for post_id or category_id
		$post_id     = $result['post_id'] ?? null;
		$category_id = $result['category_id'] ?? null;

		if ( ! $post_id && ! $category_id ) {
			$verification['success']  = false;
			$verification['errors'][] = 'No post_id or category_id in result';

			return $verification;
		}

		// Verify post if post_id
		if ( $post_id ) {


			$post = get_post( $post_id );
			if ( ! $post ) {
				$verification['success']  = false;
				$verification['errors'][] = 'Post ID ' . $post_id . ' not found in database';

				return $verification;
			}



			// Check title
			if ( empty( $post->post_title ) ) {
				$verification['warnings'][] = 'Post title is empty';

			} elseif ( $post->post_title === 'undefined' || $post->post_title === 'Untitled' ) {
				$verification['warnings'][] = 'Post title is "' . $post->post_title . '" (default/undefined)';
			}



			// Check content
			if ( empty( $post->post_content ) ) {
				$verification['warnings'][] = 'Post content is empty';
			}



			// Check featured image
			if ( post_type_supports( $post->post_type, 'thumbnail' ) ) {
				if ( ! has_post_thumbnail( $post_id ) ) {
					$verification['warnings'][] = 'No featured image set';
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '⚠️  VERIFY: No featured image' );
					}
				} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '✅ VERIFY: Featured image set' );
				}
			}

			// Check categories
			$categories = wp_get_post_categories( $post_id );
			if ( empty( $categories ) ) {
				$verification['warnings'][] = 'No categories assigned';
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( '⚠️  VERIFY: No categories' );
				}
			} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( '✅ VERIFY: Categories assigned: ' . implode( ', ', $categories ) );
			}

			// Check RankMath SEO
			if ( class_exists( 'RankMath' ) ) {
				$seo_title = get_post_meta( $post_id, 'rank_math_title', true );
				$seo_desc  = get_post_meta( $post_id, 'rank_math_description', true );

				if ( empty( $seo_title ) ) {
					$verification['warnings'][] = 'RankMath SEO title not set';
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '⚠️  VERIFY: RankMath title missing' );
					}
				} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '✅ VERIFY: RankMath title set' );
				}

				if ( empty( $seo_desc ) ) {
					$verification['warnings'][] = 'RankMath SEO description not set';
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '⚠️  VERIFY: RankMath description missing' );
					}
				} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '✅ VERIFY: RankMath description set' );
				}
			}

			// Check WPML
			if ( function_exists( 'wpml_get_language_information' ) ) {
				$lang_info = wpml_get_language_information( $post_id );

				// CRITICAL: Check if WP_Error (can happen with WPML)
				if ( is_wp_error( $lang_info ) ) {
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '⚠️  VERIFY: wpml_get_language_information returned WP_Error: ' . $lang_info->get_error_message() );
					}
					// Don't add to warnings - this is a WPML issue, not an import issue
				} elseif ( ! $lang_info || empty( $lang_info['locale'] ) ) {
					$verification['warnings'][] = 'WPML language not set';
					if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '⚠️  VERIFY: WPML language missing' );
					}
				} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
						error_log( '✅ VERIFY: WPML language set: ' . $lang_info['locale'] );
				}
			}
		}

		// Verify category if category_id
		if ( $category_id ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( 'VERIFY: Checking category ID: ' . $category_id );
			}

			$taxonomy = $result['taxonomy'] ?? 'category';
			$term     = get_term( $category_id, $taxonomy );

			if ( ! $term || is_wp_error( $term ) ) {
				$verification['success']  = false;
				$verification['errors'][] = 'Category ID ' . $category_id . ' not found';
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( '❌ VERIFY: Category not found' );
				}
				return $verification;
			}

			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( '✅ VERIFY: Category exists: ' . $term->name );
			}

			if ( empty( $term->description ) ) {
				$verification['warnings'][] = 'Category description is empty';
				if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
					error_log( '⚠️  VERIFY: Category description empty' );
				}
			}
		}

		if ( $verification['success'] ) {
			if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
				error_log( '✅ VERIFY: Verification passed' . ( ! empty( $verification['warnings'] ) ? ' (with warnings)' : '' ) );
			}
		}

		return $verification;
	}

	/**
	 * Get default import options for CRON
	 *
	 * Returns sensible defaults when no specific options provided
	 */
	public static function get_default_options() {
		return array(
			'post_status' => 'publish',  // Default to publish for CRON
			'author_id'   => 1,  // Admin user
			'categories'  => array(),  // Let auto-assignment handle it
		);
	}
}
