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

class Wisewand_Payload_Builder {

	private $options;
	private $logger;

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

	public function build_payload( $keyword_data, $user_overrides = array() ) {
		$defaults    = $this->get_default_payload_settings( $keyword_data );
		$auto_config = $this->generate_auto_config( $keyword_data );

		$payload = array_merge( $defaults, $auto_config, $user_overrides );

		$this->logger->debug(
			'Built Wisewand payload',
			array(
				'keyword'    => $keyword_data['keyword'] ?? 'unknown',
				'type'       => $payload['type'],
				'lang'       => $payload['lang'],
				'project_id' => $payload['project_id'] ?? 'none',
			)
		);

		return $payload;
	}

	private function get_default_payload_settings( $keyword_data = array() ) {
		$site_url = home_url();

		// Get language from keyword first, fallback to settings
		$keyword_lang     = $keyword_data['language_code'] ?? null;
		$keyword_location = $keyword_data['location_code'] ?? null;

		// Determine language and country
		if ( $keyword_lang ) {
			$lang = $keyword_lang;
		} else {
			$lang = $this->options->get( 'wisewand_fallback_language', 'en' );
		}

		if ( $keyword_location ) {
			// Map location_code to country
			if ( ! class_exists( 'Wisewand\\Utils\\Location_Mapper' ) ) {
				require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/Location_Mapper.php';
			}
			$country = \Wisewand\Utils\Location_Mapper::location_to_country( $keyword_location );
		} else {
			$country = $this->options->get( 'wisewand_fallback_country', 'us' );
		}

		// Select persona based on language
		$persona_id = $lang === 'fr'
			? $this->options->get( 'wisewand_default_persona_fr', '' )
			: $this->options->get( 'wisewand_default_persona_en', '' );

		// Select audio voice based on language
		$audio_voice_id = $lang === 'fr'
			? $this->options->get( 'wisewand_default_audio_voice_fr', 'jSrrwmj13CIlQAXPpk4X' )
			: $this->options->get( 'wisewand_default_audio_voice_en', 'EXAVITQu4vr4xnSDxMaL' );

		// Get country name
		$country_names = array(
			'us' => 'United States',
			'fr' => 'France',
			'gb' => 'United Kingdom',
			'ca' => 'Canada',
			'de' => 'Germany',
			'es' => 'Spain',
			'it' => 'Italy',
			'be' => 'Belgium',
			'ch' => 'Switzerland',
		);
		$country_name  = $country_names[ $country ] ?? 'United States';

		return array(
			// Language & Location (from keyword or fallback)
			'lang'                             => $lang,
			'country'                          => $country,

			// Project & Persona (from settings)
			'project_id'                       => $this->options->get( 'wisewand_default_project_id', '' ),
			'persona_id'                       => $persona_id,
			'writing_style_mode'               => ! empty( $persona_id ) ? 'persona' : 'auto',

			// Content Settings (from settings)
			'length'                           => $this->options->get( 'wisewand_default_length', 'auto' ),
			'type'                             => 'blog', // Default to blog

			// Content Features (from settings)
			'use_toc'                          => $this->options->get( 'wisewand_default_use_toc', true ),
			'use_faq'                          => $this->options->get( 'wisewand_default_use_faq', true ),
			'use_bulletlist'                   => $this->options->get( 'wisewand_default_use_bulletlist', true ),
			'use_infotable'                    => $this->options->get( 'wisewand_default_use_infotable', false ),
			'use_boldkeywords'                 => $this->options->get( 'wisewand_default_use_boldkeywords', true ),
			'use_externalsources'              => $this->options->get( 'wisewand_default_use_externalsources', true ),
			'use_summary'                      => $this->options->get( 'wisewand_default_use_summary', true ),
			'use_blockquotes'                  => $this->options->get( 'wisewand_default_use_blockquotes', true ),

			// Media Features (from settings)
			'use_image'                        => $this->options->get( 'wisewand_default_use_image', true ),
			// Auto-enable inline images if count > 0 (UX improvement: setting count should enable feature)
			'use_inlineimages'                 => $this->options->get( 'wisewand_default_use_inlineimages', false ) || $this->options->get( 'wisewand_default_inline_images_count', 1 ) > 0,
			'inlineimages_count'               => $this->options->get( 'wisewand_default_inline_images_count', 1 ), // Number of inline images (1-10)
			'use_social'                       => $this->options->get( 'wisewand_default_use_social', false ),
			'use_audio'                        => $this->options->get( 'wisewand_default_use_audio', false ),
			'audio_voice_id'                   => $audio_voice_id,

			// Image Settings (from settings)
			'image_ratio'                      => $this->options->get( 'wisewand_default_image_ratio', 'landscape' ),
			'image_use_palette'                => $this->options->get( 'wisewand_default_image_use_palette', false ),
			'image_primary_color'              => $this->options->get( 'wisewand_default_image_primary_color', '#3b82f6' ),
			'image_secondary_color'            => $this->options->get( 'wisewand_default_image_secondary_color', '#1e3a8a' ),

			'inline_images_ratio'              => $this->options->get( 'wisewand_default_inline_images_ratio', 'landscape' ),
			'inline_images_use_palette'        => $this->options->get( 'wisewand_default_inline_images_use_palette', false ),
			'inline_images_primary_color'      => $this->options->get( 'wisewand_default_inline_images_primary_color', '#3b82f6' ),
			'inline_images_secondary_color'    => $this->options->get( 'wisewand_default_inline_images_secondary_color', '#1e3a8a' ),

			// Internal Links (from settings)
			'use_internallinks'                => $this->options->get( 'wisewand_default_use_internallinks', true ),
			'use_indexed_pages_internal_links' => $this->options->get( 'wisewand_default_use_indexed_pages_internal_links', true ),
			'use_wp_internal_links'            => false,
			'use_app_internal_links'           => false,
			'use_list_internal_links'          => false,
			'internal_links_wp_status'         => $this->options->get( 'wisewand_default_internal_links_wp_status', array( 'publish' ) ),

			// Auto-set fields
			'website'                          => $site_url,
			'use_webhook'                      => false,
			'keep_title'                       => false,
			'use_cta'                          => false,
			'ctas'                             => array(),

			// AI Instructions (empty by default, auto-generated)
			'keywords_secondary'               => '',
			'search_intention_answer'          => '',
			'avoid_information'                => '',
			'additional_information'           => '',
		);
	}

	/**
	 * Generate auto-config for required fields only
	 *
	 * IMPORTANT: This method ONLY sets fields that MUST be auto-generated:
	 * - subject, title, target_keyword (from keyword)
	 * - AI instructions (context-aware)
	 *
	 * It does NOT override user's feature settings (use_infotable, use_image, etc.)
	 * Those come from admin settings and should not be overridden.
	 *
	 * @param array $keyword_data Keyword information
	 * @return array Auto-generated configuration (non-feature fields only)
	 */
	private function generate_auto_config( $keyword_data ) {
		$keyword  = $keyword_data['keyword'] ?? '';
		$intent   = $keyword_data['search_intent'] ?? 'informational';
		$volume   = $keyword_data['search_volume'] ?? 0;
		$position = $keyword_data['current_position'] ?? null;

		// ONLY auto-generate required content fields
		// DO NOT set use_infotable, use_image, or other feature toggles
		// Those are controlled by user's settings!
		$config = array(
			'subject'        => $keyword,
			'title'          => $keyword,
			'target_keyword' => $keyword,
		);

		// Generate AI instructions only if setting enabled
		// User can choose to keep blank and generate manually in Edit Publication modal
		$auto_generate = $this->options->get( 'wisewand_default_auto_generate_instructions', false );

		if ( $auto_generate ) {
			// Auto-generate using templates (user enabled in settings)
			if ( $position && $position <= 20 ) {
				$config['search_intention_answer'] = $this->generate_intention_for_improvement( $keyword, $position );
				$config['additional_information']  = $this->generate_improvement_instructions( $keyword, $position );
			} else {
				$config['search_intention_answer'] = $this->generate_intention_for_new( $keyword, $intent );
				$config['additional_information']  = $this->generate_new_content_instructions( $keyword, $intent );
			}

			$config['avoid_information'] = $this->generate_avoid_information( $keyword );
		}
		// else: Leave blank - user can generate manually in Edit Publication modal
		// using "Quick Generate" (template) or "AI Generate" (ChatGPT) buttons

		// NOTE: Removed use_infotable auto-override (was line 149)
		// User's settings from admin should control all use_* features

		return $config;
	}

	private function generate_intention_for_improvement( $keyword, $position ) {
		return sprintf(
			'This article aims to improve our current ranking (position #%d) for "%s" by providing more comprehensive, up-to-date information and better user experience.',
			$position,
			$keyword
		);
	}

	private function generate_intention_for_new( $keyword, $intent ) {
		$intent_descriptions = array(
			'informational' => 'provide comprehensive, factual information to educate readers about',
			'commercial'    => 'help readers make informed purchase decisions regarding',
			'transactional' => 'guide users through the process of',
			'navigational'  => 'help users find resources and information about',
		);

		$description = $intent_descriptions[ $intent ] ?? $intent_descriptions['informational'];

		return sprintf( 'This article will %s "%s" with practical examples and actionable insights.', $description, $keyword );
	}

	private function generate_improvement_instructions( $keyword, $position ) {
		return sprintf(
			'Focus on improving our existing content for "%s" (currently ranked #%d). ' .
			'Add fresh insights, update statistics to %s, include practical examples, ' .
			'and ensure the content is more comprehensive than competing pages. ' .
			'Identify gaps in our current coverage and fill them.',
			$keyword,
			$position,
			gmdate( 'Y' )
		);
	}

	private function generate_new_content_instructions( $keyword, $intent ) {
		$instructions = array(
			'informational' => 'Provide in-depth, well-researched information with clear structure, practical examples, and actionable takeaways.',
			'commercial'    => 'Include detailed comparisons, pros/cons, pricing information, and clear recommendations to help buyers make decisions.',
			'transactional' => 'Create step-by-step guides with clear instructions, tips for success, and common pitfalls to avoid.',
			'navigational'  => 'Provide clear navigation to resources, comprehensive overview, and links to relevant sections.',
		);

		$base_instruction = $instructions[ $intent ] ?? $instructions['informational'];

		return sprintf(
			'Create comprehensive content about "%s". %s Focus on %s best practices and current trends.',
			$keyword,
			$base_instruction,
			gmdate( 'Y' )
		);
	}

	private function generate_avoid_information( $keyword ) {
		return sprintf(
			'Avoid outdated information, unverified claims, and overly promotional content. ' .
			'Do not include generic filler content or information not directly relevant to "%s". ' .
			'Avoid speculation without factual basis.',
			$keyword
		);
	}

	private function get_country_code_from_language() {
		$lang = $this->options->get( 'wisewand_calendar_default_language', 'en' );

		$mapping = array(
			'fr' => 'fr',
			'en' => 'us',
			'de' => 'de',
			'es' => 'es',
			'it' => 'it',
		);

		return $mapping[ $lang ] ?? 'us';
	}

	private function get_country_name_from_language() {
		$lang = $this->options->get( 'wisewand_calendar_default_language', 'en' );

		$mapping = array(
			'fr' => 'France',
			'en' => 'United States',
			'de' => 'Germany',
			'es' => 'Spain',
			'it' => 'Italy',
		);

		return $mapping[ $lang ] ?? 'United States';
	}

	public function merge_user_edits( $base_payload, $user_edits ) {
		foreach ( $user_edits as $key => $value ) {
			if ( $value !== null && $value !== '' ) {
				$base_payload[ $key ] = $value;
			}
		}

		if ( isset( $user_edits['ctas'] ) && is_array( $user_edits['ctas'] ) ) {
			$base_payload['ctas']    = $user_edits['ctas'];
			$base_payload['use_cta'] = ! empty( $user_edits['ctas'] );
		}

		return $base_payload;
	}

	public function validate_payload( $payload ) {
		$required_fields = array( 'subject', 'target_keyword', 'lang', 'type' );

		foreach ( $required_fields as $field ) {
			if ( empty( $payload[ $field ] ) ) {
				return new \WP_Error( 'missing_field', sprintf( 'Required field "%s" is missing', $field ) );
			}
		}

		return true;
	}

	public function extract_colors_from_site() {
		// This method is now legacy/fallback.
		// Colors are primarily handled via explicit settings in get_default_payload_settings
		// But we keep this for backward compatibility or if needed for other logic.
		$primary_color   = '#ffffff';
		$secondary_color = '#ffffff';

		if ( function_exists( 'wp_get_custom_css' ) ) {
			$custom_css = wp_get_custom_css();

			if ( preg_match( '/#([0-9a-fA-F]{6})/', $custom_css, $matches ) ) {
				$primary_color = '#' . $matches[1];
			}
		}

		return array(
			'primary'   => $primary_color,
			'secondary' => $secondary_color,
		);
	}

	/**
	 * Generate AI-powered instructions using OpenAI GPT-4o-mini
	 * Uses structured output for high-quality, specific content briefs
	 *
	 * @param array $keyword_data Keyword information with context
	 * @return array|WP_Error Generated instructions or error
	 */
	public function generate_ai_instructions( $keyword_data ) {
		// Check if OpenAI is available
		if ( ! class_exists( 'Wisewand\\Utils\\OpenAI_Client' ) ) {
			require_once WISEWAND_PLUGIN_DIR . 'includes/Utils/OpenAI_Client.php';
		}

		if ( ! \Wisewand\Utils\OpenAI_Client::is_configured() ) {
			return new \WP_Error( 'no_api_key', 'OpenAI API key not configured' );
		}

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

		$keyword    = $keyword_data['keyword'] ?? '';
		$intent     = $keyword_data['search_intent'] ?? 'informational';
		$volume     = $keyword_data['search_volume'] ?? 0;
		$difficulty = $keyword_data['difficulty'] ?? 50;
		$position   = $keyword_data['current_position'] ?? null;
		$language   = $keyword_data['language_code'] ?? 'en';

		// Build comprehensive prompt
		$messages = array(
			array(
				'role'    => 'system',
				'content' => $this->get_ai_instructions_system_prompt(),
			),
			array(
				'role'    => 'user',
				'content' => wp_json_encode(
					array(
						'task'         => 'generate_content_brief',
						'keyword_data' => array(
							'keyword'          => $keyword,
							'search_intent'    => $intent,
							'search_volume'    => $volume,
							'difficulty'       => $difficulty,
							'current_position' => $position,
							'language'         => $language,
						),
						'context'      => array(
							'is_ranking'    => ! empty( $position ),
							'target_action' => $position ? 'improve_ranking' : 'create_new_content',
							'year'          => gmdate( 'Y' ),
						),
					),
					JSON_PRETTY_PRINT
				),
			),
		);

		// Use structured output for guaranteed valid response
		$response = $openai->chat_completion(
			$messages,
			array(
				'temperature'     => 0.4,
				'max_tokens'      => 800,
				'response_format' => array(
					'type'        => 'json_schema',
					'json_schema' => array(
						'name'   => 'content_brief_generation',
						'strict' => true,
						'schema' => array(
							'type'                 => 'object',
							'properties'           => array(
								'search_intention'        => array(
									'type'        => 'string',
									'description' => 'Clear, specific purpose and target audience (1-2 sentences)',
								),
								'additional_instructions' => array(
									'type'        => 'string',
									'description' => 'Detailed, actionable content requirements (2-4 sentences)',
								),
								'avoid_information'       => array(
									'type'        => 'string',
									'description' => 'Specific pitfalls to avoid for this keyword (1-2 sentences)',
								),
								'confidence'              => array(
									'type'        => 'number',
									'description' => 'Confidence in recommendations 0.0-1.0',
								),
							),
							'required'             => array( 'search_intention', 'additional_instructions', 'avoid_information', 'confidence' ),
							'additionalProperties' => false,
						),
					),
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return $response;
		}

		return array(
			'search_intention_answer' => $response['search_intention'] ?? '',
			'additional_information'  => $response['additional_instructions'] ?? '',
			'avoid_information'       => $response['avoid_information'] ?? '',
			'confidence'              => $response['confidence'] ?? 0.8,
		);
	}

	/**
	 * System prompt for AI instructions generation
	 * Ensures AI generates specific, actionable briefs (not generic)
	 */
	/**
	 * System prompt for AI instructions generation
	 * UNIVERSAL for any website/niche - analyzes keyword context
	 */
	private function get_ai_instructions_system_prompt() {
		return 'You are an expert SEO content strategist and editor.

MISSION: Generate a SPECIFIC, actionable content brief based on keyword analysis.

CRITICAL REQUIREMENTS:
- Analyze the keyword to infer target audience and intent
- Be SPECIFIC to this keyword - NOT generic advice
- Work for ANY website niche (don\'t assume bedtime stories, e-commerce, etc.)
- Base recommendations on search intent, volume, and difficulty data

ANALYZE AND DETERMINE:
1. WHO is searching (infer from keyword and intent)
2. WHY they are searching (what problem are they solving?)
3. WHAT content will satisfy them (topics, depth, format)
4. HOW to approach it (structure, tone, key points)

AVOID GENERIC PHRASES:
❌ "Create comprehensive content about [keyword]"
❌ "Provide in-depth information"
❌ "Include practical examples and best practices"

BE SPECIFIC BASED ON KEYWORD ANALYSIS:
✅ If keyword suggests comparison: "Compare X vs Y with pros/cons table"
✅ If keyword is how-to: "Provide step-by-step instructions with numbered list"
✅ If keyword is commercial: "Include pricing comparison and buyer recommendations"
✅ If keyword shows expertise level: Adjust complexity accordingly

CONSIDER DATA PROVIDED:
- Search Intent: informational/commercial/transactional → guides content type
- Search Volume: high = competitive topic, need depth; low = niche, be specific
- Difficulty: high = need authority signals; low = can be straightforward
- Current Position: if ranking, focus on improvement gaps
- Language: consider cultural context and local preferences

OUTPUT STRUCTURE:
{
  "search_intention": "1-2 sentences explaining WHO searches and WHY",
  "additional_instructions": "2-4 sentences with specific, actionable guidance",
  "avoid_information": "1-2 sentences about what NOT to include",
  "confidence": 0.0-1.0
}

EXAMPLES (showing variety):

Keyword: "best CRM software 2025"
→ search_intention: "Target business owners and sales managers comparing CRM solutions for purchasing decisions. Commercial intent focused on finding the optimal tool for their business size and needs."
→ additional_instructions: "Create detailed comparison table with pricing, features, and ideal business sizes. Include pros/cons for each option. Focus on 2025-specific features like AI integration and automation. Provide clear recommendation based on use case."
→ avoid_information: "Avoid outdated 2023-2024 information and discontinued products. Don\'t include affiliate disclosures that appear biased."

Keyword: "comment faire un gateau au chocolat"
→ search_intention: "Cibler les cuisiniers débutants cherchant une recette simple et fiable de gâteau au chocolat. Intent informationnel avec besoin d\'instructions claires."
→ additional_instructions: "Fournir une recette étape par étape avec temps de cuisson précis et liste d\'ingrédients mesurée. Inclure des astuces pour éviter les erreurs courantes. Ajouter des variantes (sans gluten, vegan) et conseils de conservation."
→ avoid_information: "Éviter les recettes trop complexes ou nécessitant du matériel professionnel. Ne pas inclure d\'histoire personnelle longue avant la recette."

Be adaptable, specific, and helpful for ANY website niche.';
	}
}
