<?php

/**
 * OpenAI Provider Class
 *
 * Handles all OpenAI API interactions for content generation
 *
 * @link       https://insya.com/ai-magic
 * @since      1.0.0
 *
 * @package    Ai_Magic
 * @subpackage Ai_Magic/admin
 */
class AI_Magic_OpenAI implements AI_Magic_Provider_Interface
{
    /**
     * The URL for the OpenAI API service
     *
     * @var string
     */
    private $api_url;

    /**
     * The API key used for authentication with the OpenAI API
     *
     * @var string
     */
    private $api_key;

    /**
     * The maximum number of tokens to generate
     *
     * @var int
     */
    private $max_tokens;

    /**
     * Controls the randomness of the output (higher value means more randomness)
     *
     * @var float
     */
    private $temperature;

    /**
     * Controls the diversity of token probabilities
     *
     * @var float
     */
    private $top_p;

    /**
     * Penalizes the frequency of new tokens
     *
     * @var float
     */
    private $frequency_penalty;

    /**
     * Penalizes the presence of specific tokens
     *
     * @var float
     */
    private $presence_penalty;

    /**
     * Stream response flag
     *
     * @var bool
     */
    private $stream;

    /**
     * Log probabilities count
     *
     * @var int
     */
    private $logprobs;

    /**
     * Stop sequences
     *
     * @var mixed
     */
    private $stop;

    /**
     * Engine type
     *
     * @var string
     */
    private $engine;

    /**
     * Model name
     *
     * @var string
     */
    private $model;

    /**
     * Rate limit delay
     *
     * @var int
     */
    private $rate_limit;

    /**
     * Chat-compatible models list
     *
     * @var array
     */
    private $chatModels;

    /**
     * Provider ID
     *
     * @var string
     */
    private $provider_id = 'openai';

    /**
     * Constructor - Initialize OpenAI provider with settings
     *
     * @since    1.0.0
     */
    public function __construct()
    {
        // Set the API URL for OpenAI service
        $this->api_url = 'https://api.openai.com/v1/%s';

        // Load provider-specific settings
        $this->load_provider_settings();

        // Define chat-compatible models (Updated December 2025)
        $this->chatModels = array(
            "gpt-5",
            "gpt-4o",
            "gpt-4o-mini",
            "o3-mini",
            "o1-preview",
            "o1-mini",
            "gpt-4-turbo",
            "gpt-4",
            "gpt-4-0613",
            "gpt-4-0314",
            "gpt-3.5-turbo-16k-0613",
            "gpt-3.5-turbo-16k",
            "gpt-3.5-turbo-0613",
            "gpt-3.5-turbo-0301",
            "gpt-3.5-turbo"
        );

        // Set max execution time for long API calls
        if (function_exists('ini_set')) {
            @ini_set('max_execution_time', 2000);
        }
    }

    /**
     * Load provider-specific settings from database
     *
     * @since    1.0.8
     */
    private function load_provider_settings()
    {
        // Try to get provider-specific settings first, fall back to legacy settings
        $this->api_key = get_option('ai_magic_api_key_openai', '');
        if (empty($this->api_key)) {
            // Fallback to legacy option
            $this->api_key = get_option('ai_magic_api_key', '');
        }

        // Get provider-specific model or fall back to global model
        $this->model = get_option('ai_magic_openai_model', '');
        if ($this->model === 'custom') {
            $this->model = get_option('ai_magic_openai_custom_model', '');
        }
        if (empty($this->model)) {
            $this->model = get_option('ai_magic_model', 'gpt-4-turbo');
        }

        // Get provider-specific settings with defaults
        $this->max_tokens = (int) get_option('ai_magic_openai_max_tokens', get_option('ai_magic_max_tokens', 4000));
        $this->temperature = (float) get_option('ai_magic_openai_temperature', get_option('ai_magic_temperature', 0.7));
        $this->top_p = (float) get_option('ai_magic_openai_top_p', get_option('ai_magic_top_p', 1.0));
        $this->frequency_penalty = (float) get_option('ai_magic_openai_frequency_penalty', get_option('ai_magic_frequency_penalty', 0));
        $this->presence_penalty = (float) get_option('ai_magic_openai_presence_penalty', get_option('ai_magic_presence_penalty', 0));

        // Other settings
        $this->engine = get_option('ai_magic_engine', '');
        $this->stream = (bool) get_option('ai_magic_stream', false);
        $this->logprobs = (int) get_option('ai_magic_logprobs', 0);
        $this->stop = get_option('ai_magic_stop', '');
        $this->rate_limit = (int) get_option('ai_magic_rate_limit', 1);
    }

    /**
     * Get current provider settings
     *
     * @since    1.0.8
     * @return   array    Current settings
     */
    public function get_settings()
    {
        return array(
            'model' => $this->model,
            'max_tokens' => $this->max_tokens,
            'temperature' => $this->temperature,
            'top_p' => $this->top_p,
            'frequency_penalty' => $this->frequency_penalty,
            'presence_penalty' => $this->presence_penalty
        );
    }

    public function sendRequest($data)
    {

        // Create an empty array to store the parameters
        $params = array();

        if (!empty($data['prompt'])) {
            $params['prompt'] = $data['prompt'];
        }
        if (!empty($this->max_tokens)) {
            $params['max_tokens'] = (int) $this->max_tokens;
        }
        if (!empty($this->temperature)) {
            $params['temperature'] = (float) $this->temperature;
        }
        if (!empty($this->top_p)) {
            $params['top_p'] = (float) $this->top_p;
        }
        if (!empty($this->frequency_penalty)) {
            $params['frequency_penalty'] = (float) $this->frequency_penalty;
        }
        if (!empty($this->presence_penalty)) {
            $params['presence_penalty'] = (float) $this->presence_penalty;
        }

        $params['stream'] = false;

        // API request headers
        $headers = array(
            'Authorization' => 'Bearer ' . $this->api_key,
            'Content-Type' => 'application/json',
        );

        # https://platform.openai.com/docs/api-reference/introduction
        $endpoints = array(
            'chat' => array('method' => 'POST', 'path' => "chat/completions"),
            'completion' => array('method' => 'POST', 'path' => sprintf("engines/%s/completions", $this->model)),
            'completions' => array('method' => 'POST', 'path' => 'completions'),
            'moderations' => array('method' => 'GET', 'path' => 'moderations'), // Content moderation related operations
            'classifications' => array('method' => 'GET', 'path' => 'classifications'), // Text classification tasks
            'embeddings' => array('method' => 'GET', 'path' => 'embeddings'), // Text embeddings
            'image' => array('method' => 'POST', 'path' => 'images/generations'), // Image-related operations
            'images' => array('method' => 'GET', 'path' => 'images'), // Image-related operations
            'answers' => array('method' => 'POST', 'path' => 'answers'), // Providing answers to questions
            'models' => array('method' => 'GET', 'path' => 'models'), // Model information and management
            'chat/completions' => array('method' => 'POST', 'path' => 'chat/completions'), // Chat conversation completions
            'fine_tuning/jobs' => array('method' => 'POST', 'path' => 'fine_tuning/jobs'), // Fine-tuning job operations

            'search' => array('method' => 'GET', 'path' => sprintf("engine/%s", $this->model)), // Search operations for a specific engine
            'engines/engine' => array('method' => 'GET', 'path' => sprintf("engines/%s", $this->model)),

            'engines' => array('method' => 'GET', 'path' => 'engines'), // List of engines and engine details
            'list-engines' => array('method' => 'GET', 'path' => 'engines/list'), // List of available engines
            'user' => array('method' => 'GET', 'path' => 'users'), // User account-related operations
            'get-usage' => array('method' => 'GET', 'path' => 'usage/%s'), // Retrieve usage information for a user
            'list-usage' => array('method' => 'GET', 'path' => 'usage'), // List of usage data
        );

        $section = 'completion';

        // Check if using a Chat model
        if (in_array($this->model, $this->chatModels) || strpos($this->model, 'gpt-') === 0) {

            $params['model'] = $this->model;
            $params['messages'] = array(
                array('role' => 'user', 'content' => $params['prompt'])
            );

            unset($params['prompt']);
            unset($params['best_of']);

            // Chat models don't support some parameters in the same way, clean up if needed
            // But generally max_tokens, temperature etc are fine.

            $section = 'chat';

        }

        $endpoint = $endpoints[$section]['path'];
        $method = $endpoints[$section]['method'];

        $api_url = sprintf($this->api_url, $endpoint);

        // Make the API request
        if ($method == 'POST') {

            $response = wp_safe_remote_post($api_url, array(
                'timeout' => 1000,
                'sslverify' => false,
                'headers' => $headers,
                'body' => wp_json_encode($params),
            ));

        } else {

            $response = wp_safe_remote_get($api_url, array(
                'timeout' => 1000,
                'sslverify' => false,
                'headers' => $headers,
                'body' => wp_json_encode($params),
            ));
        }

        sleep($this->rate_limit);

        return $response;
    }

    public function parseContent($text)
    {

        // Belirtilen anahtar kelimelere dayanarak alanları çıkar
        $fields = array("title", "slug", "excerpt", "tags", "content");
        $parsed_data = array();

        foreach ($fields as $field) {
            // Improved regex: Case insensitive, handles optional spaces, looks for #field: value
            preg_match("/#\s*$field\s*:\s*(.*?)(?=#\s*\w+\s*:|$)/si", $text, $matches);
            $parsed_data[$field] = isset($matches[1]) ? trim($matches[1]) : "";
        }

        // Fallback: If content is empty, try to use the whole text if it doesn't look like structured data
        if (empty($parsed_data['content']) && empty($parsed_data['title'])) {
            $parsed_data['content'] = $text;
        }

        return (object) $parsed_data;
    }

    public function generateText($title_text)
    {

        $start_time = microtime(true);

        $prompt = $this->buildPrompt($title_text);

        // Log the prompt for debugging
        error_log('AI Magic Prompt: ' . $prompt);

        $max_execution_time = ini_get('max_execution_time');

        if ($max_execution_time < 1000) {

            return ['type' => 'error', 'message' => __('It appears that your PHP INI max execution time is less than 1000 seconds. Please increase it to ensure that the plugin functions properly', 'ai_magic')];

        }

        $response = $this->sendRequest([
            'prompt' => $prompt,
        ]);

        // Log raw response
        if (!is_wp_error($response)) {
            error_log('AI Magic Raw Response: ' . wp_remote_retrieve_body($response));
        } else {
            error_log('AI Magic API Error: ' . $response->get_error_message());
        }


        // Make API call here
        // Let's assume $response holds the API response

        if (!is_wp_error($response)) {

            // Decode the JSON response to an associative array
            $response_data = json_decode(wp_remote_retrieve_body($response), true);

            // Check if there is a warning, usually indicating a deprecated model or another issue
            if (isset($response_data['warning'])) {
                // Log the warning or take other necessary actions
                error_log('OpenAI Warning: ' . $response_data['warning']);
            }

            // Check for errors in the API response
            if (isset($response_data['error'])) {
                // Return an error message
                return ['type' => 'error', 'message' => $response_data['error']['message']];
            }

            if (isset($response_data['choices'][0]['finish_reason']) && $response_data['choices'][0]['finish_reason'] === 'length') {
                // Log warning but continue to process partial content
                error_log('OpenAI Warning: Response truncated due to max_tokens limit.');
            }

            // Extract text based on model type (Chat vs Completion)
            $generated_text = '';
            if (isset($response_data['choices'][0]['text'])) {
                $generated_text = $response_data['choices'][0]['text'];
            } elseif (isset($response_data['choices'][0]['message']['content'])) {
                $generated_text = $response_data['choices'][0]['message']['content'];
            }

            // If everything is okay, proceed to extract the text data
            if (!empty($generated_text)) {

                $content = $this->parseContent($generated_text);

                if (!$content) {
                    return ['type' => 'error', 'message' => __('Invalid content creation. Please try again.', 'ai_magic')];
                }

                $post_data = array(
                    'post_title' => wp_strip_all_tags($content->title),
                    'post_excerpt' => $content->excerpt,
                    'post_content' => $content->content,
                    'post_name' => $content->slug,
                    'post_tags' => $content->tags,
                    'post_status' => 'publish',
                    'post_type' => 'ai_magic_logs',
                    'post_author' => get_current_user_id()
                );

                $post_id = wp_insert_post($post_data);

                $end_time = microtime(true);
                $duration = ($end_time - $start_time) * 1000;

                update_post_meta($post_id, 'duration', $duration);
                update_post_meta($post_id, 'prompt', $title_text);
                update_post_meta($post_id, 'tags', $content->tags);
                update_post_meta($post_id, 'prompt_tokens', $response_data['usage']['prompt_tokens']);
                update_post_meta($post_id, 'completion_tokens', $response_data['usage']['completion_tokens']);
                update_post_meta($post_id, 'total_tokens', $response_data['usage']['total_tokens']);
                update_post_meta($post_id, 'model', $response_data['model']);
                update_post_meta($post_id, 'chat_id', $response_data['id']);

                // Calculate and store cost
                $input_tokens = $response_data['usage']['prompt_tokens'];
                $output_tokens = $response_data['usage']['completion_tokens'];
                $model = $response_data['model'];
                $cost = AI_Magic_Cost_Calculator::calculate_cost($model, $input_tokens, $output_tokens);

                update_post_meta($post_id, '_ai_magic_cost', $cost);
                update_post_meta($post_id, '_ai_magic_input_tokens', $input_tokens);
                update_post_meta($post_id, '_ai_magic_output_tokens', $output_tokens);

                // Save to History
                if (class_exists('Ai_Magic_History')) {
                    Ai_Magic_History::save(array(
                        'post_id' => $post_id,
                        'title' => wp_strip_all_tags($content->title),
                        'prompt' => $title_text,
                        'content' => $content->content,
                        'model' => $model,
                        'tokens_used' => $response_data['usage']['total_tokens'],
                        'generation_time' => $duration / 1000, // Convert ms to seconds
                        'cost' => $cost
                    ));
                }

                // Return success message along with the text data
                return [
                    'type' => 'success',
                    'message' => 'Success',
                    'data' => $post_data,
                    'raw_text' => $generated_text, // Include raw text for fallback
                    'cost' => $cost,
                    'cost_formatted' => AI_Magic_Cost_Calculator::format_cost($cost),
                    'input_tokens' => $input_tokens,
                    'output_tokens' => $output_tokens
                ];
            } else {
                // Return a message indicating the text could not be extracted
                return ['type' => 'error', 'message' => __('Text data could not be extracted from the API response.', 'ai_magic')];
            }
        } else {
            // Log the error or take other necessary actions
            return ['type' => 'error', 'message' => __('An error occurred while making the API request.', 'ai_magic')];
            ;
        }
    }

    /**
     * Generate SEO meta description
     *
     * @since    1.0.7
     * @param    string    $title      Post title
     * @param    string    $content    Post content (optional)
     * @param    array     $keywords   Focus keywords (optional)
     * @return   array                 Response with meta description
     */
    public function generateMetaDescription($title, $content = '', $keywords = array())
    {

        $keyword_text = !empty($keywords) ? implode(', ', $keywords) : '';

        $prompt = "Write a compelling SEO meta description for an article titled \"$title\".";

        if (!empty($content)) {
            $content_preview = substr(strip_tags($content), 0, 500);
            $prompt .= " The article is about: $content_preview";
        }

        if (!empty($keyword_text)) {
            $prompt .= " Include these keywords naturally: $keyword_text.";
        }

        $prompt .= " The meta description must be between 150-160 characters, engaging, and encourage clicks. Return only the meta description text, nothing else.";

        $response = $this->sendRequest([
            'prompt' => $prompt,
        ]);

        if (!is_wp_error($response)) {
            $response_data = json_decode(wp_remote_retrieve_body($response), true);

            if (isset($response_data['error'])) {
                return ['type' => 'error', 'message' => $response_data['error']['message']];
            }

            // Extract text from response
            $meta_description = '';
            if (isset($response_data['choices'][0]['text'])) {
                $meta_description = trim($response_data['choices'][0]['text']);
            } elseif (isset($response_data['choices'][0]['message']['content'])) {
                $meta_description = trim($response_data['choices'][0]['message']['content']);
            }

            // Ensure it's within character limit
            if (strlen($meta_description) > 160) {
                $meta_description = substr($meta_description, 0, 157) . '...';
            }

            return [
                'type' => 'success',
                'message' => 'Meta description generated successfully',
                'data' => $meta_description,
                'length' => strlen($meta_description)
            ];
        } else {
            return ['type' => 'error', 'message' => __('An error occurred while generating meta description.', 'ai_magic')];
        }
    }

    /**
     * Generate focus keywords from content
     *
     * @since    1.0.7
     * @param    string    $content    Post content
     * @param    int       $count      Number of keywords to generate
     * @return   array                 Response with keywords
     */
    public function generateFocusKeywords($content, $count = 5)
    {

        $content_preview = substr(strip_tags($content), 0, 1000);

        $prompt = "Analyze this content and extract the $count most important SEO keywords or key phrases. Return only a comma-separated list of keywords, nothing else:\n\n$content_preview";

        $response = $this->sendRequest([
            'prompt' => $prompt,
        ]);

        if (!is_wp_error($response)) {
            $response_data = json_decode(wp_remote_retrieve_body($response), true);

            if (isset($response_data['error'])) {
                return ['type' => 'error', 'message' => $response_data['error']['message']];
            }

            // Extract keywords
            $keywords_text = '';
            if (isset($response_data['choices'][0]['text'])) {
                $keywords_text = trim($response_data['choices'][0]['text']);
            } elseif (isset($response_data['choices'][0]['message']['content'])) {
                $keywords_text = trim($response_data['choices'][0]['message']['content']);
            }

            // Convert to array
            $keywords = array_map('trim', explode(',', $keywords_text));
            $keywords = array_filter($keywords); // Remove empty values

            return [
                'type' => 'success',
                'message' => 'Keywords generated successfully',
                'data' => $keywords
            ];
        } else {
            return ['type' => 'error', 'message' => __('An error occurred while generating keywords.', 'ai_magic')];
        }
    }
    /**
     * Get available models from OpenAI
     * 
     * @return array
     */
    public function getModels()
    {
        if (empty($this->api_key)) {
            return [];
        }

        $url = sprintf($this->api_url, 'models');

        $response = wp_safe_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->api_key,
            ],
            'timeout' => 30
        ]);

        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) {
            return [];
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (empty($body['data'])) {
            return [];
        }

        $models = [];
        foreach ($body['data'] as $model) {
            $models[] = [
                'id' => $model['id'],
                'name' => $model['id']
            ];
        }

        return $models;
    }

    /**
     * Validate API Key
     * 
     * @return bool|WP_Error
     */
    public function validateApiKey()
    {
        if (empty($this->api_key)) {
            return new WP_Error('missing_key', __('API Key is missing', 'ai_magic'));
        }

        $models = $this->getModels();

        if (empty($models)) {
            return new WP_Error('invalid_key', __('Invalid API Key or connection error', 'ai_magic'));
        }

        return true;
    }

    /**
     * Build the prompt string based on settings and input
     * 
     * @param string $title_text The user input/title
     * @param array $overrides Optional overrides for settings (language, tone, etc.)
     * @return string The constructed prompt
     */
    public function buildPrompt($title_text, $overrides = array())
    {
        include plugin_dir_path(dirname(__FILE__)) . 'includes/class-ai-magic-vars.php';

        // Retrieve settings, checking overrides first
        $writing_language = isset($overrides['language']) ? $overrides['language'] : get_option('ai_magic_writing_language', "en");
        $writing_style = isset($overrides['style']) ? $overrides['style'] : get_option('ai_magic_writing_style', "infor");
        $writing_tone = isset($overrides['tone']) ? $overrides['tone'] : get_option('ai_magic_writing_tone', "formal");
        $word_count = isset($overrides['word_count']) ? $overrides['word_count'] : get_option('ai_magic_min_content_length', 500);
        $keyword_count = get_option('ai_magic_max_keyword', 3);

        // Handle keywords if passed in overrides
        if (isset($overrides['keywords']) && !empty($overrides['keywords'])) {
            // If specific keywords are provided, we might want to append them to the prompt or handle them differently
            // For now, let's just ensure the prompt logic can use them if we update the template
        }

        // Translate options
        $lang_code = $writing_language; // Save raw code for logic
        $writing_language = isset($languageOptions[$writing_language]) ? $languageOptions[$writing_language] : $writing_language;
        $writing_style = isset($writingStyleOptions[$writing_style]) ? $writingStyleOptions[$writing_style] : $writing_style;
        $writing_tone = isset($writingToneOptions[$writing_tone]) ? $writingToneOptions[$writing_tone] : $writing_tone;

        // Define language-specific prompts with human-like writing instructions
        $prompts = [
            'tr' => '
You are a professional content writer. Create a natural, original article about "[title]" ENTIRELY IN TURKISH that search engines will recognize as human-written.

IMPORTANT: Write the article ONLY IN TURKISH. Do not use English words.

CRITICAL WRITING RULES:
- Vary sentence length (mix short, medium, and long sentences)
- Diversify paragraph structures (some 2-3 sentences, others 5-6)
- Use transition phrases (however, on the other hand, therefore, moreover, for instance - use Turkish equivalents)
- Balance active and passive voice
- Include rhetorical questions and answer them
- Use occasional personal narrative tone
- Explain technical terms, avoid jargon
- Provide concrete examples and scenarios

CONTENT REQUIREMENTS:
- Minimum length: [word_count] words
- Tone: [tone]
- Style: [style]
- HTML formatting: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Subheadings must be engaging and intriguing
- Introduction paragraph must hook the reader
- Conclusion must include summary and call-to-action

OUTPUT FORMAT:
#title: [Turkish title]
#slug: [slug]
#excerpt: [Turkish excerpt]
#tags: [Turkish tags]
#content: [Turkish article content]
            ',

            'es' => '
Eres un escritor de contenido profesional. Crea un artículo COMPLETAMENTE EN ESPAÑOL sobre "[title]" que los motores de búsqueda reconocerán como escrito por humanos.

IMPORTANTE: Escribe el artículo SOLO EN ESPAÑOL. No uses palabras en inglés.

REGLAS CRÍTICAS DE ESCRITURA:
- Varía la longitud de las oraciones (mezcla oraciones cortas, medianas y largas)
- Diversifica las estructuras de párrafos (algunos de 2-3 oraciones, otros de 5-6)
- Usa frases de transición (sin embargo, por otro lado, por lo tanto, además, por ejemplo)
- Equilibra oraciones activas y pasivas
- Incluye preguntas retóricas y respóndelas
- Usa ocasionalmente un tono narrativo personal
- Explica términos técnicos, evita la jerga
- Proporciona ejemplos concretos y escenarios

REQUISITOS DE CONTENIDO:
- Longitud mínima: [word_count] palabras
- Tono: [tone]
- Estilo: [style]
- Formato HTML: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Los subtítulos deben ser atractivos e intrigantes
- El párrafo de introducción debe captar al lector
- La conclusión debe incluir resumen y llamada a la acción

FORMATO DE SALIDA:
#title: [título en español]
#slug: [slug]
#excerpt: [resumen en español]
#tags: [etiquetas en español]
#content: [contenido del artículo en español]
            ',

            'fr' => '
Vous êtes un rédacteur de contenu professionnel. Créez un article ENTIÈREMENT EN FRANÇAIS sur "[title]" que les moteurs de recherche reconnaîtront comme écrit par des humains.

IMPORTANT: Rédigez l\'article UNIQUEMENT EN FRANÇAIS. N\'utilisez pas de mots anglais.

RÈGLES CRITIQUES D\'ÉCRITURE:
- Variez la longueur des phrases (mélangez phrases courtes, moyennes et longues)
- Diversifiez les structures de paragraphes (certains de 2-3 phrases, d\'autres de 5-6)
- Utilisez des phrases de transition (cependant, d\'autre part, par conséquent, de plus, par exemple)
- Équilibrez les phrases actives et passives
- Incluez des questions rhétoriques et répondez-y
- Utilisez occasionnellement un ton narratif personnel
- Expliquez les termes techniques, évitez le jargon
- Fournissez des exemples concrets et des scénarios

EXIGENCES DE CONTENU:
- Longueur minimale: [word_count] mots
- Ton: [tone]
- Style: [style]
- Format HTML: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Les sous-titres doivent être accrocheurs et intrigants
- Le paragraphe d\'introduction doit captiver le lecteur
- La conclusion doit inclure un résumé et un appel à l\'action

FORMAT DE SORTIE:
#title: [titre en français]
#slug: [slug]
#excerpt: [résumé en français]
#tags: [étiquettes en français]
#content: [contenu de l\'article en français]
            ',

            'de' => '
Sie sind ein professioneller Content-Autor. Erstellen Sie einen Artikel VOLLSTÄNDIG AUF DEUTSCH über "[title]", den Suchmaschinen als von Menschen geschrieben erkennen werden.

WICHTIG: Schreiben Sie den Artikel NUR AUF DEUTSCH. Verwenden Sie keine englischen Wörter.

KRITISCHE SCHREIBREGELN:
- Variieren Sie die Satzlänge (mischen Sie kurze, mittlere und lange Sätze)
- Diversifizieren Sie Absatzstrukturen (einige mit 2-3 Sätzen, andere mit 5-6)
- Verwenden Sie Übergangssätze (jedoch, andererseits, daher, außerdem, zum Beispiel)
- Balancieren Sie aktive und passive Sätze
- Fügen Sie rhetorische Fragen ein und beantworten Sie diese
- Verwenden Sie gelegentlich einen persönlichen Erzählton
- Erklären Sie Fachbegriffe, vermeiden Sie Jargon
- Geben Sie konkrete Beispiele und Szenarien

INHALTSANFORDERUNGEN:
- Mindestlänge: [word_count] Wörter
- Ton: [tone]
- Stil: [style]
- HTML-Format: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Untertitel sollten fesselnd und faszinierend sein
- Der Einleitungsabsatz sollte den Leser fesseln
- Der Schluss sollte eine Zusammenfassung und einen Aufruf zum Handeln enthalten

AUSGABEFORMAT:
#title: [Titel auf Deutsch]
#slug: [slug]
#excerpt: [Zusammenfassung auf Deutsch]
#tags: [Tags auf Deutsch]
#content: [Artikelinhalt auf Deutsch]
            ',

            'it' => '
Sei un autore di contenuti professionista. Crea un articolo COMPLETAMENTE IN ITALIANO su "[title]" che i motori di ricerca riconosceranno come scritto da umani.

IMPORTANTE: Scrivi l\'articolo SOLO IN ITALIANO. Non usare parole inglesi.

REGOLE CRITICHE DI SCRITTURA:
- Varia la lunghezza delle frasi (mescola frasi brevi, medie e lunghe)
- Diversifica le strutture dei paragrafi (alcuni di 2-3 frasi, altri di 5-6)
- Usa frasi di transizione (tuttavia, d\'altra parte, pertanto, inoltre, ad esempio)
- Bilancia frasi attive e passive
- Includi domande retoriche e rispondi
- Usa occasionalmente un tono narrativo personale
- Spiega i termini tecnici, evita il gergo
- Fornisci esempi concreti e scenari

REQUISITI DEL CONTENUTO:
- Lunghezza minima: [word_count] parole
- Tono: [tone]
- Stile: [style]
- Formato HTML: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- I sottotitoli devono essere accattivanti e intriganti
- Il paragrafo introduttivo deve catturare il lettore
- La conclusione deve includere un riepilogo e una chiamata all\'azione

FORMATO DI OUTPUT:
#title: [titolo in italiano]
#slug: [slug]
#excerpt: [riassunto in italiano]
#tags: [tag in italiano]
#content: [contenuto dell\'articolo in italiano]
            ',

            'pt' => '
Você é um escritor de conteúdo profissional. Crie um artigo COMPLETAMENTE EM PORTUGUÊS sobre "[title]" que os motores de busca reconhecerão como escrito por humanos.

IMPORTANTE: Escreva o artigo APENAS EM PORTUGUÊS. Não use palavras em inglês.

REGRAS CRÍTICAS DE ESCRITA:
- Varie o comprimento das frases (misture frases curtas, médias e longas)
- Diversifique as estruturas de parágrafos (alguns com 2-3 frases, outros com 5-6)
- Use frases de transição (no entanto, por outro lado, portanto, além disso, por exemplo)
- Equilibre frases ativas e passivas
- Inclua perguntas retóricas e responda-as
- Use ocasionalmente um tom narrativo pessoal
- Explique termos técnicos, evite jargão
- Forneça exemplos concretos e cenários

REQUISITOS DE CONTEÚDO:
- Comprimento mínimo: [word_count] palavras
- Tom: [tone]
- Estilo: [style]
- Formato HTML: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Os subtítulos devem ser cativantes e intrigantes
- O parágrafo introdutório deve capturar o leitor
- A conclusão deve incluir um resumo e uma chamada para ação

FORMATO DE SAÍDA:
#title: [título em português]
#slug: [slug]
#excerpt: [resumo em português]
#tags: [tags em português]
#content: [conteúdo do artigo em português]
            ',

            'ru' => '
Вы профессиональный автор контента. Создайте статью ПОЛНОСТЬЮ НА РУССКОМ ЯЗЫКЕ о "[title]", которую поисковые системы распознают как написанную человеком.

ВАЖНО: Пишите статью ТОЛЬКО НА РУССКОМ ЯЗЫКЕ. Не используйте английские слова.

КРИТИЧЕСКИЕ ПРАВИЛА НАПИСАНИЯ:
- Варьируйте длину предложений (смешивайте короткие, средние и длинные предложения)
- Разнообразьте структуры абзацев (некоторые из 2-3 предложений, другие из 5-6)
- Используйте переходные фразы (однако, с другой стороны, поэтому, кроме того, например)
- Балансируйте активные и пассивные предложения
- Включайте риторические вопросы и отвечайте на них
- Иногда используйте личный повествовательный тон
- Объясняйте технические термины, избегайте жаргона
- Приводите конкретные примеры и сценарии

ТРЕБОВАНИЯ К КОНТЕНТУ:
- Минимальная длина: [word_count] слов
- Тон: [tone]
- Стиль: [style]
- HTML формат: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Подзаголовки должны быть привлекательными и интригующими
- Вступительный абзац должен захватить читателя
- Заключение должно включать резюме и призыв к действию

ФОРМАТ ВЫВОДА:
#title: [заголовок на русском]
#slug: [slug]
#excerpt: [резюме на русском]
#tags: [теги на русском]
#content: [содержание статьи на русском]
            ',

            'ja' => '
あなたはプロのコンテンツライターです。「[title]」に関する記事を完全に日本語で作成してください。検索エンジンが人間が書いたと認識する自然な記事にしてください。

重要: 記事は日本語のみで書いてください。英語の単語を使用しないでください。

重要な執筆ルール:
- 文の長さを変える（短い文、中程度の文、長い文を混ぜる）
- 段落構造を多様化する（2-3文の段落もあれば、5-6文の段落もある）
- 接続表現を使用する（しかし、一方で、したがって、さらに、例えば）
- 能動態と受動態のバランスを取る
- 修辞的な質問を含め、それに答える
- 時々個人的な語り口調を使用する
- 専門用語を説明し、ジャーゴンを避ける
- 具体的な例とシナリオを提供する

コンテンツ要件:
- 最小文字数: [word_count] 文字
- トーン: [tone]
- スタイル: [style]
- HTMLフォーマット: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- 小見出しは魅力的で興味をそそるものにする
- 導入段落は読者を引き付ける
- 結論には要約と行動喚起を含める

出力形式:
#title: [日本語のタイトル]
#slug: [slug]
#excerpt: [日本語の要約]
#tags: [日本語のタグ]
#content: [日本語の記事内容]
            ',

            'zh' => '
您是一位专业的内容作者。请创建一篇关于"[title]"的文章，完全使用中文撰写，让搜索引擎识别为人类撰写。

重要: 文章必须完全使用中文。不要使用英文单词。

关键写作规则:
- 变化句子长度（混合短句、中句和长句）
- 多样化段落结构（有些2-3句，有些5-6句）
- 使用过渡短语（然而、另一方面、因此、此外、例如）
- 平衡主动句和被动句
- 包含修辞性问题并回答
- 偶尔使用个人叙述语气
- 解释技术术语，避免行话
- 提供具体示例和场景

内容要求:
- 最小长度: [word_count] 字
- 语气: [tone]
- 风格: [style]
- HTML格式: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- 副标题应引人入胜且有趣
- 引言段落应吸引读者
- 结论应包括摘要和行动号召

输出格式:
#title: [中文标题]
#slug: [slug]
#excerpt: [中文摘要]
#tags: [中文标签]
#content: [中文文章内容]
            ',

            'ar' => '
أنت كاتب محتوى محترف. أنشئ مقالة باللغة العربية بالكامل حول "[title]" ستتعرف عليها محركات البحث على أنها مكتوبة بواسطة البشر.

مهم: اكتب المقالة باللغة العربية فقط. لا تستخدم كلمات إنجليزية.

قواعد الكتابة الحرجة:
- تنويع طول الجمل (امزج الجمل القصيرة والمتوسطة والطويلة)
- تنويع هياكل الفقرات (بعضها من 2-3 جمل، والبعض الآخر من 5-6)
- استخدم عبارات انتقالية (ومع ذلك، من ناحية أخرى، لذلك، بالإضافة إلى ذلك، على سبيل المثال)
- توازن الجمل النشطة والسلبية
- قم بتضمين أسئلة بلاغية وأجب عليها
- استخدم أحيانًا نبرة سردية شخصية
- اشرح المصطلحات التقنية، تجنب المصطلحات المتخصصة
- قدم أمثلة وسيناريوهات ملموسة

متطلبات المحتوى:
- الحد الأدنى للطول: [word_count] كلمة
- النبرة: [tone]
- الأسلوب: [style]
- تنسيق HTML: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- يجب أن تكون العناوين الفرعية جذابة ومثيرة للاهتمام
- يجب أن تجذب الفقرة التمهيدية القارئ
- يجب أن يتضمن الختام ملخصًا ودعوة للعمل

تنسيق الإخراج:
#title: [العنوان بالعربية]
#slug: [slug]
#excerpt: [الملخص بالعربية]
#tags: [العلامات بالعربية]
#content: [محتوى المقالة بالعربية]
            '
        ];

        // Default English prompt (most advanced)
        // Default Dynamic Prompt (for all other languages)
        $default_prompt = '
You are a professional content writer. Create a natural, original article about "[title]" ENTIRELY IN [language] that search engines will recognize as human-written.

IMPORTANT: Write the article ONLY IN [language]. Do not use words from other languages.

CRITICAL WRITING RULES:
- Vary sentence length (mix short, medium, and long sentences)
- Diversify paragraph structures (some 2-3 sentences, others 5-6)
- Use transition phrases (appropriate for the language)
- Balance active and passive voice
- Include rhetorical questions and answer them
- Use occasional personal narrative tone
- Explain technical terms, avoid jargon
- Provide concrete examples and scenarios
- Add unexpected insights or perspectives
- Use storytelling elements where appropriate

CONTENT REQUIREMENTS:
- Minimum length: [word_count] words
- Tone: [tone]
- Style: [style]
- HTML formatting: <h1>, <h2>, <h3>, <p>, <ul>, <li>, <strong>, <em>
- Subheadings must be engaging and intriguing
- Introduction paragraph must hook the reader
- Conclusion must include summary and call-to-action

OUTPUT FORMAT:
#title: [title in [language]]
#slug: [slug]
#excerpt: [excerpt in [language]]
#tags: [tags in [language]]
#content: [article content in [language]]
        ';

        // Select appropriate prompt based on language code
        $prompt = $default_prompt;
        foreach ($prompts as $lang_prefix => $lang_prompt) {
            if (strpos($lang_code, $lang_prefix) === 0) {
                $prompt = $lang_prompt;
                break;
            }
        }

        $prompt = str_replace('[title]', $title_text, $prompt);
        $prompt = str_replace('[slug]', sanitize_title($title_text), $prompt);
        $prompt = str_replace('[excerpt]', 'A brief summary of the article.', $prompt); // Placeholder for instruction
        $prompt = str_replace('[tags]', 'comma, separated, tags', $prompt); // Placeholder
        $prompt = str_replace('[content]', 'The full article content here...', $prompt); // Placeholder

        $prompt = str_replace('[language]', $writing_language, $prompt);
        $prompt = str_replace('[style]', $writing_style, $prompt);
        $prompt = str_replace('[tone]', $writing_tone, $prompt);
        $prompt = str_replace('[word_count]', $word_count, $prompt);
        $prompt = str_replace('[keyword_count]', $keyword_count, $prompt);

        // Add custom instructions if provided
        if (isset($overrides['instructions']) && !empty($overrides['instructions'])) {
            $prompt .= "\n\nAdditional Instructions: " . $overrides['instructions'];
        }

        // Add keywords if provided
        if (isset($overrides['keywords']) && !empty($overrides['keywords'])) {
            $prompt .= "\n\nFocus Keywords: " . $overrides['keywords'];
        }

        $prompt = str_replace("[title]", $title_text, $prompt);
        $prompt = str_replace("[language]", $writing_language, $prompt);
        $prompt = str_replace("[style]", strtolower($writing_style), $prompt);
        $prompt = str_replace("[tone]", strtolower($writing_tone), $prompt);
        $prompt = str_replace("[word_count]", strtolower($word_count), $prompt);
        $prompt = str_replace("[keyword_count]", strtolower($keyword_count), $prompt);

        // Apply global base prompt / company context
        if (!class_exists('AI_Magic_Context')) {
            require_once plugin_dir_path(dirname(__FILE__)) . 'includes/class-ai-magic-context.php';
        }
        $prompt = AI_Magic_Context::apply_context($prompt);

        return $prompt;
    }
}
