<?php
/**
 * FAQ generator prompt factory.
 *
 * Extracts prompt construction from FAQGeneratorService for consistency
 * with DescriptionPromptFactory / StandardPromptFactory / SeoMetaPromptFactory patterns.
 *
 * @package AIPT\Api\BulkGenerator\FAQ\Core
 */

namespace AIPT\Api\BulkGenerator\FAQ\Core;

use AIPT\Utils\PromptFormatter;

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

/**
 * Factory class for building FAQ generation prompts.
 *
 * Uses Markdown+XML hybrid structure following v2.6.2 prompt engineering patterns.
 * Includes FAQ-specific quality gates for customer-focused content.
 *
 * @since 2.6.2
 */
class FAQPromptFactory {

    /**
     * Build system and user prompts using XML hybrid structure.
     *
     * Updated in v2.6.2 based on prompt engineering research:
     * - Uses Markdown headers for structure (# Identity, # Rules)
     * - XML tags for data isolation (<product_data>, <task>, <output_format>)
     * - Positive instructions instead of "don't do X"
     * - Feature→Benefit→Meaning transformation guidance
     *
     * @param array $options
     * @param array $product_data
     * @param \WC_Product $product
     * @return array{system_prompt:string,user_prompt:string}
     */
    public function build_prompt_payload(array $options, array $product_data, $product): array {
        $format = $options['format'];
        $mode = $options['mode'];
        $faq_count = $options['faq_count'];
        $language = $options['language'];
        $sources = $options['sources'];

        $source_context = $this->build_source_context($sources, $product_data, $product);

        $system_prompt = $this->build_system_prompt($language, $faq_count, $format, $mode);

        $user_prompt = $this->build_user_prompt($source_context, $faq_count, $options);

        $user_prompt = PromptFormatter::formatProductVariables($user_prompt, $this->enrich_product_variables($product, $product_data));

        return [
            'system_prompt' => $system_prompt,
            'user_prompt' => $user_prompt,
        ];
    }

	/**
	 * Build the optimized system prompt using Markdown + XML hybrid structure.
	 *
	 * @param string $language Target language.
	 * @param int    $faq_count Number of FAQs to generate.
	 * @param string $format Output format (text/html).
	 * @param string $mode Generation mode (questions/answers/both).
	 * @return string System prompt.
	 */
	private function build_system_prompt(string $language, int $faq_count, string $format, string $mode): string {
        $language           = sanitize_text_field($language);
        $format_instruction = $this->get_format_instruction($format, $mode, $faq_count);

        return "# Identity
You are an e-commerce FAQ specialist who anticipates customer questions and provides clear, helpful answers.

# Language & Style
- Language: {$language}
- Tone: Helpful, clear, and customer-focused
- Write questions customers would actually ask (natural language, not robotic)
- Answers should be concise yet complete

# Core Rules
1. Generate questions that address REAL buyer concerns (shipping, sizing, compatibility, care, usage)
2. Apply the \"What would I want to know before buying?\" test to each FAQ
3. Be SPECIFIC—use actual product details, not generic responses
4. Questions should be SEO-friendly (include relevant keywords naturally)
5. Answers should build confidence and reduce purchase hesitation

# Quality Gate
Before finalizing, verify each FAQ passes this test:
- Would a real customer ask this question?
- Does the answer actually help them make a buying decision?
- Is the language natural and conversational?

{$format_instruction}";
    }

	/**
	 * Get format-specific output instructions with XML wrapper.
	 *
	 * @param string $format Output format.
	 * @param string $mode Generation mode.
	 * @param int    $faq_count Number of FAQs.
	 * @return string Format instruction.
	 */
	private function get_format_instruction(string $format, string $mode, int $faq_count): string {
        $lines = array();
        $lines[] = '<output_format>';
        $lines[] = "Generate exactly {$faq_count} FAQ entries.";
        $lines[] = '';

        switch ($format) {
            case 'text':
                if ($mode === 'questions') {
                    $lines[] = 'Format: Plain text, one question per line';
                    $lines[] = 'Structure:';
                    $lines[] = 'Q: [Complete question ending with ?]';
                    $lines[] = '';
                    $lines[] = 'Rules:';
                    $lines[] = "- Exactly {$faq_count} lines, each starting with \"Q: \"";
                    $lines[] = '- No answers, no blank lines, no numbering';
                } elseif ($mode === 'answers') {
                    $lines[] = 'Format: Plain text, one answer per line';
                    $lines[] = 'Structure:';
                    $lines[] = 'A: [Complete answer]';
                    $lines[] = '';
                    $lines[] = 'Rules:';
                    $lines[] = "- Exactly {$faq_count} lines, each starting with \"A: \"";
                    $lines[] = '- No questions, no blank lines, no numbering';
                } else {
                    $lines[] = 'Format: Plain text Q&A pairs';
                    $lines[] = 'Structure (repeat exactly ' . $faq_count . ' times):';
                    $lines[] = 'Q: [Question ending with ?]';
                    $lines[] = 'A: [Answer]';
                    $lines[] = '';
                    $lines[] = '[blank line between pairs]';
                    $lines[] = '';
                    $lines[] = 'Rules:';
                    $lines[] = '- One question and one answer per pair';
                    $lines[] = '- Single blank line separates each FAQ pair';
                    $lines[] = '- No numbering, bullets, or extra commentary';
                }
                break;

            default: 
                $lines[] = 'Format: HTML definition list';
                $lines[] = 'Structure:';
                $lines[] = '<dl class="aipt-faq-list">';
                $lines[] = '  <dt>[Question]</dt>';
                $lines[] = '  <dd>[Answer]</dd>';
                $lines[] = "  <!-- repeat {$faq_count} times -->";
                $lines[] = '</dl>';
                $lines[] = '';
                $lines[] = 'Rules:';
                $lines[] = "- Exactly {$faq_count} <dt>/<dd> pairs inside one <dl>";
                $lines[] = '- No scripts, styles, or markup outside the <dl>';

                if ($mode === 'questions') {
                    $lines[] = '- Leave <dd></dd> empty (answers not requested)';
                } elseif ($mode === 'answers') {
                    $lines[] = '- Leave <dt></dt> empty, place answer in <dd>';
                }
                break;
        }

        $lines[] = '';
        $lines[] = 'Return ONLY the formatted output. No explanations or additional text.';
        $lines[] = '</output_format>';

        return implode("\n", $lines);
    }

	/**
	 * Build the user prompt with XML data isolation.
	 *
	 * @param string $source_context Product context.
	 * @param int    $faq_count Number of FAQs.
	 * @param array  $options Generation options (values must be pre-sanitized by caller).
	 * @return string User prompt.
	 */
	private function build_user_prompt(string $source_context, int $faq_count, array $options): string {
		$parts = array();

		$parts[] = "<product_data>\n{$source_context}\n</product_data>";

		if ( ! empty( $options['global_additional_prompt'] ) ) {
			$global_prompt = sanitize_textarea_field( (string) $options['global_additional_prompt'] );
			if ( '' !== $global_prompt ) {
				$parts[] = "<global_instructions>\n" . $global_prompt . "\n</global_instructions>";
			}
		}

		if ( ! empty( $options['additional_prompt'] ) ) {
			$additional_prompt = sanitize_textarea_field( (string) $options['additional_prompt'] );
			if ( '' !== $additional_prompt ) {
				$parts[] = "<additional_instructions>\n" . $additional_prompt . "\n</additional_instructions>";
			}
		}

        $parts[] = "<task>
Generate {$faq_count} FAQs for this product.

Focus areas:
1. Pre-purchase concerns (compatibility, sizing, what's included)
2. Usage questions (how to use, care instructions, best practices)
3. Shipping/delivery expectations
4. Product specifications customers commonly ask about

Use the product data above to create relevant, specific FAQs.
</task>";

        return implode("\n\n", $parts);
    }

    /**
     * Build source context from product data.
     *
     * @param array $sources Source types to include.
     * @param array $product_data Product data array.
     * @param \WC_Product $product WooCommerce product object.
     * @return string Source context string.
     */
    private function build_source_context(array $sources, array $product_data, $product): string {
        $sections = [];

        if (in_array('existing_title', $sources, true)) {
            $sections[] = "Title: " . sanitize_text_field($product->get_name());
        }

        if (in_array('product_description', $sources, true)) {
            $short_description = wp_strip_all_tags($product->get_short_description());
            $long_description = wp_strip_all_tags($product->get_description());

            if (!empty($short_description)) {
                $sections[] = "Short Description: " . $short_description;
            }
            if (!empty($long_description)) {
                $sections[] = "Full Description: " . $long_description;
            }
        }

        if (in_array('product_categories', $sources, true) && !empty($product_data['categories'])) {
            $sections[] = "Categories: " . (is_array($product_data['categories'])
                ? implode(', ', $product_data['categories'])
                : $product_data['categories']);
        }

        if (in_array('product_tags', $sources, true) && !empty($product_data['tags'])) {
            $sections[] = "Tags: " . (is_array($product_data['tags'])
                ? implode(', ', $product_data['tags'])
                : $product_data['tags']);
        }

        if (in_array('product_attributes', $sources, true) && !empty($product_data['formatted_attributes'])) {
            $sections[] = "Attributes: " . $product_data['formatted_attributes'];
        }

        if (empty($sections)) {
            $sections[] = "Product summary: " . wp_strip_all_tags($product->get_description());
        }

        return implode("\n", array_filter($sections));
    }

    /**
     * Enrich product variables for prompt formatting.
     *
     * @param \WC_Product $product WooCommerce product object.
     * @param array $product_data Product data array.
     * @return array Enriched variables.
     */
    private function enrich_product_variables($product, array $product_data): array {
        $variables = $product_data;

		$variables['short_description'] = wp_strip_all_tags($product->get_short_description());
		$variables['long_description'] = wp_strip_all_tags($product->get_description());
		$variables['title'] = sanitize_text_field($product->get_name());

        return $variables;
    }
}
