<?php

namespace AIPT\Api\Chatbot;

/**
 * Prompt builder for AI chatbot interactions.
 *
 * Constructs system and user prompts for AI provider calls.
 *
 * @package AIPT\Api\Chatbot
 * @since 2.5.0
 */
class PromptBuilder implements PromptBuilderInterface {

    /**
     * Tone descriptions for AI guidance.
     */
    private const TONE_DESCRIPTIONS = [
        'professional' => 'Be professional, knowledgeable, and courteous.',
        'friendly' => 'Be warm, approachable, and helpful like a friend.',
        'casual' => 'Be relaxed and conversational, using everyday language.',
        'formal' => 'Be formal, respectful, and use proper business language.',
    ];

    /**
     * Response length guidance.
     */
    private const RESPONSE_LENGTH_GUIDANCE = [
        'concise' => 'Keep responses brief and to the point (1-2 sentences).',
        'balanced' => 'Provide helpful responses with moderate detail (2-4 sentences).',
        'detailed' => 'Give comprehensive, detailed responses with explanations.',
    ];

    /**
     * Build system prompt with store context 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 (<store_context>, <guidelines>)
     * - Clear behavioral rules with quality gates
     * - Optimized for multi-turn conversations
     *
     * @param array $settings Chatbot settings.
     * @return string System prompt text.
     */
    public function buildSystemPrompt(array $settings): string {
        $bot_name = $settings['general']['bot_name'] ?? 'Shop Assistant';
        $tone = $settings['general']['tone'] ?? 'friendly';
        $language = $settings['general']['language'] ?? 'en';
        $response_length = $settings['behavior']['response_length'] ?? 'balanced';
        $recommendation_mode = $settings['behavior']['product_recommendation_mode'] ?? 'auto';

        $tone_description = self::TONE_DESCRIPTIONS[$tone] ?? self::TONE_DESCRIPTIONS['friendly'];
        $length_guidance = self::RESPONSE_LENGTH_GUIDANCE[$response_length] ?? self::RESPONSE_LENGTH_GUIDANCE['balanced'];
        $language_instruction = $this->getLanguageInstruction($language);

        $store_name = get_bloginfo('name');
        $store_description = get_bloginfo('description');
        $store_context = trim($settings['general']['store_context'] ?? '');
        $knowledge_pages = $settings['general']['knowledge_pages'] ?? [];

        $response_format = $this->buildResponseFormatInstruction($recommendation_mode);

        $store_context_section = $this->buildStoreContextSection($store_name, $store_description, $store_context, $knowledge_pages);

        $system_prompt = "# Identity\n" .
            "You are {$bot_name}, a knowledgeable shopping assistant for {$store_name}.\n\n" .
            "{$store_context_section}\n\n" .
            "# Language & Style\n" .
            "- {$tone_description}\n" .
            "- {$length_guidance}\n\n" .
            "<core_rules>\n" .
            "# What You MUST Do\n" .
            "1. Recommend ONLY products from the provided catalog—never invent products\n" .
            "2. When recommending, explain WHY it matches the customer's needs\n" .
            "3. Ask clarifying questions when the request is unclear\n" .
            "4. When mentioning products, use names from the product list. Customers may use combined words, abbreviations, or slight misspellings—match them to the closest product if the intent is clear\n" .
            "5. For products with options/variants, mention they can select preferences on the product page\n" .
            "6. For non-product questions (shipping, returns, FAQ, store policies), use the information from <store_context> to answer. If the information is not provided there, say you don't have that information and suggest contacting the store directly\n\n" .
            "# What You Must NEVER Do\n" .
            "1. Invent or suggest products not in the provided catalog\n" .
            "2. Make claims about products not stated in their descriptions\n" .
            "3. Discuss pricing or promotions unless explicitly provided\n" .
            "4. Guess when you don't have information—ask instead\n" .
            "5. Make definitive claims about stock availability—say \"should be available\" or \"appears to be in stock\" rather than absolute statements, and direct customers to click the product link for real-time availability\n" .
            "</core_rules>\n\n" .
            "<conversation_context_rules>\n" .
            "# Understanding Customer References\n" .
            "- Pronouns like \"it\", \"this\", \"that\" refer to the MOST RECENTLY discussed product\n" .
            "- Check \"Previous Conversation\" to identify which product the customer means\n" .
            "- Follow-up questions always relate to the last discussed product unless explicitly changed\n" .
            "- When customer asks \"tell me more\" or similar, expand on the SAME product\n" .
            "</conversation_context_rules>\n\n" .
            "{$response_format}\n\n" .
            "<language_requirement>\n" .
            "{$language_instruction}\n" .
            "</language_requirement>";

        return apply_filters('aipt_chatbot_system_prompt', $system_prompt, $settings);
    }

    /**
     * Build store context section with XML isolation.
     *
     * @param string $store_name        Store name.
     * @param string $store_description Store description.
     * @param string $store_context     Additional store context.
     * @param array  $knowledge_pages   Array of WordPress page IDs to include as knowledge base.
     * @return string Store context section.
     */
    private function buildStoreContextSection(string $store_name, string $store_description, string $store_context, array $knowledge_pages = []): string {
        $lines = array();
        $lines[] = '<store_context>';
        $lines[] = "Store: {$store_name}";
        
        if (!empty($store_description)) {
            $lines[] = "About: {$store_description}";
        }
        
        if (!empty($store_context)) {
            $lines[] = '';
            $lines[] = 'Additional Information:';
            $lines[] = $store_context;
        }

        $knowledge_content = $this->buildKnowledgePagesContent($knowledge_pages);
        if (!empty($knowledge_content)) {
            $lines[] = '';
            $lines[] = $knowledge_content;
        }
        
        $lines[] = '</store_context>';
        $lines[] = '';
        $lines[] = '# Your Role';
        $lines[] = '- Help customers find products that match their needs';
        $lines[] = '- Answer questions about products in the catalog';
        $lines[] = '- Answer store-related questions (shipping, returns, FAQ, policies) using the information provided in <store_context>';
        $lines[] = '- Provide helpful recommendations based on preferences';
        $lines[] = '- Guide customers through their shopping experience';

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

    /**
     * Build knowledge pages content for store context injection.
     *
     * Loads selected WordPress pages, strips HTML, and formats content
     * for AI consumption within token-efficient limits.
     *
     * @param array $page_ids Array of WordPress page IDs.
     * @return string Formatted knowledge pages content, or empty string if none.
     */
    private function buildKnowledgePagesContent(array $page_ids): string {
        if (empty($page_ids)) {
            return '';
        }

        $max_chars_per_page = 2000;
        $sections = array();

        foreach ($page_ids as $page_id) {
            $page = get_post(absint($page_id));
            if (!$page || $page->post_type !== 'page' || $page->post_status !== 'publish') {
                continue;
            }

            $content = wp_strip_all_tags($page->post_content);
            $content = preg_replace('/\s+/', ' ', $content);
            $content = trim($content);

            if (empty($content)) {
                continue;
            }

            if (mb_strlen($content, 'UTF-8') > $max_chars_per_page) {
                $content = mb_substr($content, 0, $max_chars_per_page, 'UTF-8') . '...';
            }

            $sections[] = "## {$page->post_title}";
            $sections[] = $content;
        }

        if (empty($sections)) {
            return '';
        }

        return "Knowledge Base Pages:\n" . implode("\n", $sections);
    }

    /**
     * Build response format instruction based on recommendation mode.
     *
     * @param string $mode Recommendation mode (auto|always|never).
     * @return string Response format instruction.
     */
    private function buildResponseFormatInstruction(string $mode): string {
        $base_format = "Response Format:\n" .
            "- Start with a brief, helpful response to the customer's question\n" .
            "- When mentioning products, use their EXACT name as provided in the product list\n" .
            "- The system will automatically display product cards for products you mention";

        if ($mode === 'auto') {
            return $base_format . "\n" .
                "- CRITICAL: You MUST end your response with exactly one of these tags on a new line:\n\n" .
                "  [SHOW_PRODUCTS] - Use ONLY when:\n" .
                "    * Customer explicitly asks for product recommendations (\"show me...\", \"what do you have...\", \"recommend...\")\n" .
                "    * Customer asks about a SPECIFIC product by name\n" .
                "    * Customer is actively shopping and needs to see options\n" .
                "    * Your response directly recommends or discusses specific products\n\n" .
                "  [HIDE_PRODUCTS] - Use when:\n" .
                "    * Customer asks general store questions (shipping, delivery, returns, refunds, payment methods, store hours, policies)\n" .
                "    * Greeting or farewell messages\n" .
                "    * Customer has complaints or support issues\n" .
                "    * Asking clarifying questions\n" .
                "    * Answering questions that don't require product display\n" .
                "    * Customer already knows which product they want and asks about it (price, stock, features of THAT product)\n" .
                "    * Follow-up questions about previously discussed products (no need to show cards again)\n\n" .
                "- IMPORTANT: Just because you MENTION a product name in your response does NOT mean you should show products.\n" .
                "  Example: If customer asks \"What's the shipping time for the ACME Heater I was looking at?\" - answer the shipping question with [HIDE_PRODUCTS], don't show product cards.\n\n" .
                "- DEFAULT TO [HIDE_PRODUCTS] if unsure. Only show products when the customer clearly wants to SEE and BROWSE products.\n\n" .
                "- The tag MUST be the very last thing in your response\n" .
                "- Do NOT include any text after the tag";
        }

        return $base_format;
    }

    /**
     * Build user prompt with message and product context using XML hybrid structure.
     *
     * Updated in v2.6.2:
     * - XML tags for data isolation (<customer_message>, <available_products>, <conversation_history>)
     * - Clear task specification
     * - Better handling of empty product contexts
     *
     * @param string $message   Customer's message.
     * @param array  $products  Product data for context.
     * @param array  $settings  Chatbot settings.
     * @param array  $history   Conversation history for context.
     * @param string $user_name Customer's name for personalization.
     * @return string User prompt text.
     */
    public function buildUserPrompt(string $message, array $products, array $settings, array $history = [], string $user_name = ''): string {
        $product_context = $this->formatProductContext($products, 10);
        $parts = array();

        if (!empty($user_name)) {
            $safe_name = $this->sanitizeUserInput($user_name, 50);
            if (!empty($safe_name)) {
                $parts[] = "<customer_info>\nName: {$safe_name}\nNote: Address by name when it feels natural.\n</customer_info>";
            }
        }

        if (!empty($history)) {
            $formatted_history = $this->formatConversationHistory($history);
            $parts[] = "<conversation_history>\n{$formatted_history}\n</conversation_history>";
        }

        $parts[] = "<customer_message>\n{$message}\n</customer_message>";

        if (!empty($product_context)) {
            $parts[] = "<available_products>\n{$product_context}\n</available_products>";
        } else {
            $parts[] = "<available_products>\nNo specific products match this query.\n</available_products>";
        }

        $parts[] = "<task>
Respond to the customer's message.

Guidelines:
1. Use the conversation history to understand context
2. Reference only products from <available_products>
3. If no matching products, suggest browsing or asking a different question
4. Be helpful and natural in your response
</task>";

        $user_prompt = implode("\n\n", $parts);

        return apply_filters('aipt_chatbot_user_prompt', $user_prompt, $message, $products, $settings);
    }

    /**
     * Format conversation history for prompt context.
     *
     * @param array $history Conversation history array with role and content.
     * @return string Formatted conversation history.
     */
    private function formatConversationHistory(array $history): string {
        if (empty($history)) {
            return '';
        }

        $formatted = [];
        foreach ($history as $msg) {
            $role = $msg['role'] ?? 'user';
            $content = $msg['content'] ?? '';

            if (empty($content)) {
                continue;
            }

            $content = preg_replace('/\s*\[(SHOW|HIDE)_PRODUCTS\]\s*/i', '', $content);

            $role_label = $role === 'assistant' ? 'Assistant' : 'Customer';
            $formatted[] = "{$role_label}: {$content}";
        }

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

    /**
     * Format products for prompt context with full details from index.
     *
     * @param array $products Raw product data from index.
     * @param int   $max      Maximum products to include.
     * @return string Formatted product context.
     */
    public function formatProductContext(array $products, int $max = 10): string {
        if (empty($products)) {
            return '';
        }

        $products = array_slice($products, 0, $max);
        $formatted = [];

        foreach ($products as $index => $product) {
            $num = $index + 1;
            $line = "{$num}. {$product['title']}";

            if (!empty($product['price'])) {
                $line .= " - {$product['price']}";
            }
            if (!empty($product['regular_price']) && !empty($product['sale_price']) && $product['regular_price'] !== $product['sale_price']) {
                $line .= " (was {$product['regular_price']}, now on sale)";
            }

            if (!empty($product['is_variable']) && $product['is_variable']) {
                $line .= " (has options/variants)";
            }

            if (!empty($product['stock_status'])) {
                if ($product['stock_status'] === 'outofstock') {
                    $line .= " [OUT OF STOCK]";
                } elseif ($product['stock_status'] === 'onbackorder') {
                    $line .= " [Available on Backorder]";
                } elseif (!empty($product['stock_quantity'])) {
                    $line .= " [In Stock: {$product['stock_quantity']} available]";
                } else {
                    $line .= " [In Stock]";
                }
            }

            if (!empty($product['sku'])) {
                $line .= "\n   SKU: {$product['sku']}";
            }

            $description = '';
            if (!empty($product['short_description'])) {
                $description = wp_strip_all_tags($product['short_description']);
            } elseif (!empty($product['description'])) {
                $description = wp_strip_all_tags($product['description']);
            }
            if (!empty($description)) {
                $description = substr($description, 0, 200);
                if (strlen($description) >= 200) {
                    $description .= '...';
                }
                $line .= "\n   Description: {$description}";
            }

            if (!empty($product['categories'])) {
                $categories = $this->getCategoryList($product['categories']);
                if ($categories) {
                    $line .= "\n   Categories: {$categories}";
                }
            }

            if (!empty($product['tags'])) {
                $tags = $this->getTagList($product['tags']);
                if ($tags) {
                    $line .= "\n   Tags: {$tags}";
                }
            }

            if (!empty($product['attributes']) && is_array($product['attributes'])) {
                $attr_parts = [];
                foreach ($product['attributes'] as $attr_name => $attr_value) {

                    $clean_name = preg_replace('/^pa_/', '', $attr_name);
                    $clean_name = ucfirst(str_replace(['_', '-'], ' ', $clean_name));
                    $attr_parts[] = "{$clean_name}: {$attr_value}";
                }
                if (!empty($attr_parts)) {
                    $line .= "\n   Attributes: " . implode(', ', $attr_parts);
                }
            }

            $formatted[] = $line;
        }

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

    /**
     * Get category list for prompt.
     *
     * @param array $category_ids Category IDs from index.
     * @return string Comma-separated category names.
     */
    public function getCategoryList(array $category_ids): string {
        if (empty($category_ids)) {
            return '';
        }

        $names = [];
        foreach ($category_ids as $cat_id) {
            $term = get_term($cat_id, 'product_cat');
            if ($term && !is_wp_error($term)) {
                $names[] = $term->name;
            }
        }

        return implode(', ', $names);
    }

    /**
     * Get tag list for prompt.
     *
     * @param array $tag_ids Tag IDs from index.
     * @return string Comma-separated tag names.
     */
    public function getTagList(array $tag_ids): string {
        if (empty($tag_ids)) {
            return '';
        }

        $names = [];
        foreach ($tag_ids as $tag_id) {
            $term = get_term($tag_id, 'product_tag');
            if ($term && !is_wp_error($term)) {
                $names[] = $term->name;
            }
        }

        return implode(', ', $names);
    }

    /**
     * Language data mapping: code => [englishName, nativeName]
     * Synced with CHATBOT_LANGUAGE_OPTIONS in options.ts
     */
    private const LANGUAGE_DATA = [
        'af' => ['Afrikaans', 'Afrikaans'],
        'ar' => ['Arabic', 'العربية'],
        'bg' => ['Bulgarian', 'български'],
        'bn' => ['Bengali', 'বাংলা'],
        'ca' => ['Catalan', 'català'],
        'cs' => ['Czech', 'čeština'],
        'da' => ['Danish', 'dansk'],
        'de' => ['German', 'Deutsch'],
        'el' => ['Greek', 'Ελληνικά'],
        'en' => ['English', 'English'],
        'en-GB' => ['English (UK)', 'English (UK)'],
        'es' => ['Spanish', 'Español'],
        'et' => ['Estonian', 'eesti'],
        'fa' => ['Persian', 'فارسی'],
        'fi' => ['Finnish', 'suomi'],
        'fr' => ['French', 'français'],
        'he' => ['Hebrew', 'עברית'],
        'hi' => ['Hindi', 'हिन्दी'],
        'hr' => ['Croatian', 'hrvatski'],
        'hu' => ['Hungarian', 'magyar'],
        'id' => ['Indonesian', 'Indonesia'],
        'it' => ['Italian', 'italiano'],
        'ja' => ['Japanese', '日本語'],
        'ko' => ['Korean', '한국어'],
        'lt' => ['Lithuanian', 'lietuvių'],
        'lv' => ['Latvian', 'latviešu'],
        'ms' => ['Malay', 'Bahasa Melayu'],
        'nl' => ['Dutch', 'Nederlands'],
        'no' => ['Norwegian', 'norsk'],
        'pl' => ['Polish', 'polski'],
        'pt' => ['Portuguese', 'português'],
        'ro' => ['Romanian', 'română'],
        'ru' => ['Russian', 'русский'],
        'sr' => ['Serbian', 'Srpski'],
        'sk' => ['Slovak', 'slovenčina'],
        'sl' => ['Slovenian', 'slovenščina'],
        'sv' => ['Swedish', 'svenska'],
        'th' => ['Thai', 'ไทย'],
        'tr' => ['Turkish', 'Türkçe'],
        'uk' => ['Ukrainian', 'українська'],
        'ur' => ['Urdu', 'اردو'],
        'vi' => ['Vietnamese', 'Tiếng Việt'],
        'zh' => ['Chinese', '中文'],
        'zh-TW' => ['Chinese (Traditional)', '繁體中文'],
    ];

    /**
     * Get language instruction for AI.
     *
     * Instructs the AI to detect and respond in the customer's language.
     * Falls back to the configured language if detection fails.
     *
     * @param string $fallback_language Fallback language code if detection fails.
     * @return string Language instruction.
     */
    private function getLanguageInstruction(string $fallback_language): string {
        $lang_data = self::LANGUAGE_DATA[$fallback_language] ?? self::LANGUAGE_DATA['en'];
        $fallback_name = $lang_data[0];
        $fallback_native = $lang_data[1];

        $fallback_display = $fallback_name;
        if ($fallback_name !== $fallback_native && strpos($fallback_language, 'en') !== 0) {
            $fallback_display = "{$fallback_name} ({$fallback_native})";
        }

        return "CRITICAL: You MUST detect the language of the customer's message and respond in the SAME language.\n" .
            "- If the customer writes in Turkish, respond in Turkish.\n" .
            "- If the customer writes in German, respond in German.\n" .
            "- If the customer writes in Spanish, respond in Spanish.\n" .
            "- Match the customer's language exactly, regardless of your default settings.\n" .
            "- If you cannot determine the language, default to {$fallback_display}.";
    }

    /**
     * Build a simple greeting response prompt.
     *
     * @param array $settings Chatbot settings.
     * @return string Greeting system prompt.
     */
    public function buildGreetingPrompt(array $settings): string {
        $bot_name = $settings['general']['bot_name'] ?? 'Shop Assistant';
        $greeting = $settings['general']['greeting_message'] ?? 'Hi! How can I help you find the perfect product today?';

        return "You are {$bot_name}. Greet the customer with: \"{$greeting}\"";
    }

    /**
     * Extract product IDs mentioned in AI response.
     *
     * Uses fuzzy matching to handle variations in product name formatting.
     *
     * @param string $response AI response text.
     * @param array  $products Available products.
     * @return array Product IDs mentioned.
     */
    public function extractMentionedProducts(string $response, array $products): array {
        $mentioned = [];
        $response_normalized = $this->normalizeForMatching($response);

        foreach ($products as $product) {
            $title = $product['title'] ?? '';
            if (empty($title)) {
                continue;
            }

            $title_normalized = $this->normalizeForMatching($title);
            if (strpos($response_normalized, $title_normalized) !== false) {
                $mentioned[] = $product['product_id'];
                continue;
            }

            if ($this->hasSignificantWordMatch($response_normalized, $title_normalized, 2)) {
                $mentioned[] = $product['product_id'];
            }
        }

        return array_unique($mentioned);
    }

    /**
     * Normalize text for matching.
     *
     * Converts to lowercase, replaces dashes/underscores with spaces,
     * and removes extra whitespace.
     *
     * @param string $text Text to normalize.
     * @return string Normalized text.
     */
    private function normalizeForMatching(string $text): string {
        $text = strtolower($text);
        $text = str_replace(['-', '_', '–', '—'], ' ', $text);
        $text = preg_replace('/\s+/', ' ', $text);
        return trim($text);
    }

    /**
     * Check if response contains significant words from product title.
     *
     * @param string $response_normalized Normalized response text.
     * @param string $title_normalized    Normalized product title.
     * @param int    $min_matches         Minimum number of words that must match.
     * @return bool True if enough significant words match.
     */
    private function hasSignificantWordMatch(string $response_normalized, string $title_normalized, int $min_matches = 2): bool {

        $stop_words = ['the', 'a', 'an', 'and', 'or', 'for', 'with', 'in', 'on', 'at', 'to', 'of', 'is', 'are', 'was', 'were'];

        $title_words = array_filter(
            explode(' ', $title_normalized),
            function ($word) use ($stop_words) {
                return strlen($word) > 2 && !in_array($word, $stop_words, true);
            }
        );

        if (count($title_words) < $min_matches) {

            $min_matches = max(1, count($title_words));
        }

        $matches = 0;
        foreach ($title_words as $word) {

            if (preg_match('/\b' . preg_quote($word, '/') . '\b/', $response_normalized)) {
                $matches++;
            }
        }

        return $matches >= $min_matches;
    }

    /**
     * Sanitize user input for safe prompt interpolation.
     *
     * Prevents prompt injection by removing dangerous characters and limiting length.
     *
     * @param string $input Raw user input.
     * @param int    $max_length Maximum allowed length (default 50).
     * @return string Sanitized input safe for prompt use.
     */
    private function sanitizeUserInput(string $input, int $max_length = 50): string {
        if (empty($input)) {
            return '';
        }

        $sanitized = str_replace(["\r\n", "\r", "\n"], ' ', $input);

        $sanitized = preg_replace('/[\x00-\x1F\x7F]/', '', $sanitized);

        $sanitized = trim($sanitized);

        $sanitized = preg_replace('/\s+/', ' ', $sanitized);

        if (mb_strlen($sanitized, 'UTF-8') > $max_length) {
            $sanitized = mb_substr($sanitized, 0, $max_length, 'UTF-8');
        }

        return $sanitized;
    }
}
