// ============================================================================
// AI CONTENT EXPANSION
// ============================================================================

function expandArticleWithAI($originalTitle, $originalContent, $focusKeyword = '', $apiKey, $apiUrl, $timeout = 300) {
    $plainContent = strip_tags($originalContent);
    
    $prompt = <<<PROMPT
You are an expert AI content writer for EngineAI. Expand this short article into 3000-4000 words in English.

TITLE: {$originalTitle}
KEYWORD: {$focusKeyword}
CONTENT: {$plainContent}

Requirements:
1. Keep original topic, facts, and core message intact
2. Expand with: detailed explanations, examples, expert insights, use cases, pros/cons, future implications
3. Structure with clear H2/H3 headings, bullet points, logical flow
4. Write in professional English, SEO-optimized
5. Output ONLY clean HTML (<p>, <h2>, <h3>, <ul>, <li>, <strong>, <em>, <blockquote>)
6. No markdown, no intro text, no JSON wrapper - just article body HTML
7. Final content: 3000-4000 words

START DIRECTLY WITH EXPANDED CONTENT:
PROMPT;

    $payload = [
        'model' => defined('AI_MODEL_NAME') ? AI_MODEL_NAME : 'engineai-pro',
        'messages' => [
            ['role' => 'system', 'content' => 'You write comprehensive SEO-optimized AI articles in English.'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7,
        'max_tokens' => 6500,
        'top_p' => 0.9,
        'frequency_penalty' => 0.3
    ];

    $ch = curl_init($apiUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey,
            'Accept: application/json'
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_SSL_VERIFYPEER => true
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) return ['success' => false, 'content' => null, 'error' => 'CURL: ' . $curlError, 'word_count' => 0];
    if ($httpCode !== 200) {
        $decoded = @json_decode($response, true);
        return ['success' => false, 'content' => null, 'error' => "API $httpCode: " . ($decoded['error']['message'] ?? 'Unknown'), 'word_count' => 0];
    }
    $decoded = @json_decode($response, true);
    $expandedContent = $decoded['choices'][0]['message']['content'] ?? null;
    if (!$expandedContent) return ['success' => false, 'content' => null, 'error' => 'Empty AI response', 'word_count' => 0];

    $expandedContent = preg_replace('/^```html?\s*/i', '', $expandedContent);
    $expandedContent = preg_replace('/\s*```$/', '', $expandedContent);
    $expandedContent = trim($expandedContent);
    $newWordCount = str_word_count(strip_tags($expandedContent));
    $minWords = defined('AI_EXPAND_MIN_WORDS') ? AI_EXPAND_MIN_WORDS : 3000;
    
    if ($newWordCount < $minWords * 0.7) {
        return ['success' => false, 'content' => $expandedContent, 'error' => "Too short: {$newWordCount} words", 'word_count' => $newWordCount];
    }
    return ['success' => true, 'content' => $expandedContent, 'error' => null, 'word_count' => $newWordCount];
}

if (!function_exists('logAIRequest')) {
    function logAIRequest($message, $level = 'INFO') {
        $logFile = __DIR__ . '/ai_expansions.log';
        @file_put_contents($logFile, "[" . date('Y-m-d H:i:s') . "] [$level] $message\n", FILE_APPEND | LOCK_EX);
    }
}
<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
        xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
        xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
        xmlns:xhtml="http://www.w3.org/1999/xhtml">
</urlset>
