<?php
// /var/www/html/api/v1/ai_worker_infographic.php
if (php_sapi_name() !== 'cli') die("Only CLI access allowed");

require_once __DIR__ . '/db.php';
$conn->set_charset("utf8mb4");

$task_id = $argv[1] ?? null;
if (!$task_id) die("No task ID provided");

$log_file = __DIR__ . '/debug_ai_worker_info.txt';
file_put_contents($log_file, "\n--- СТАРТ INFOGRAPHIC: $task_id ---\n", FILE_APPEND);

$conn->query("UPDATE ai_tasks SET status = 'processing' WHERE task_id = '$task_id'");

$res = $conn->query("SELECT user_id, cost, model_type as category, mood as sub_category, style_preset as poster_style, pose as meta_data, original_image_url FROM ai_tasks WHERE task_id = '$task_id'");
if ($res->num_rows === 0) die();
$task = $res->fetch_assoc();

$user_id = $task['user_id'];
$cost = (float)$task['cost'];
$category = mb_strtolower($task['category'], 'UTF-8');
$sub_category = mb_strtolower($task['sub_category'], 'UTF-8');
$poster_style = $task['poster_style'];
$image_url = $task['original_image_url'];

// Распаковываем наши дополнительные параметры
$meta = json_decode($task['meta_data'], true) ?? [];
$product_name = $meta['product_name'] ?? 'Premium Product';
$brand = $meta['brand'] ?? '';
$features_array = $meta['features'] ?? [];
$features_text = implode(" • ", $features_array);

// Если бренд указан, добавляем его к названию
$headline = !empty($brand) ? "$brand $product_name" : $product_name;

// ==============================================================================
// 🧠 CATEGORY DNA (Система стилей на основе ваших крутых промптов)
// ==============================================================================
$dna_prompts = [
    "tech_apple" => "Premium Apple-style smartphone/gadget campaign poster, 4:5 vertical, clean modern global advertising aesthetic. Minimal white studio environment with a luminous background color panel. Soft premium studio key light. Ultra-realistic material. Ultra-clean modern sans-serif typography. Four glass feature cards at the bottom. Commercial billboard quality.",
    
    "fmcg_explosive" => "Hyper-commercial FMCG food/snack campaign poster, 4:5 vertical. Deep vibrant environment with rich gradients, dynamic motion, flying particles, glossy reflections. Atmosphere of impact and craving. Strong commercial key light. Bold condensed headline stacked tightly. High-energy layout.",
    
    "beverage_fresh" => "Premium beverage/liquid packaging advertisement poster, 4:5 vertical. Dramatic deep background with glowing light effects, floating ice cubes, fluid splash, sparkling bubbles, realistic condensation droplets. Glossy commercial lighting. Bold refreshing typography with feature badges.",
    
    "outdoor_steel" => "Premium outdoor/sports product campaign poster, 4:5 vertical. Bold large typography integrated behind the floating product. Fresh adventurous atmosphere with water or nature energy. Clean bright commercial light, strong metallic reflections. Large condensed headline, minimal feature badges.",
    
    "beauty_luxury" => "High-end luxury cosmetics and beauty campaign poster, 4:5 vertical. Soft elegant pastel or velvet background with delicate 3D floral or silk elements. Diffused flattering lighting, glossy premium reflections, ethereal glow. Elegant serif typography, minimalist feature texts. Vogue magazine aesthetic.",
    
    "universal_commercial" => "High-end professional commercial product poster, 4:5 vertical. Clean gradient studio background with a modern podium. Professional softbox lighting with realistic shadows. Bold modern typography for the headline, clean minimal feature boxes at the bottom. Elegant advertising quality."
];

// Умный роутинг (Smart Routing): Если 'auto' - выбираем сами. Если юзер выбрал сам - берем его выбор!
$selected_dna = "universal_commercial";

if ($poster_style !== 'auto' && isset($dna_prompts[$poster_style])) {
    $selected_dna = $poster_style;
} else {
    // Автоматический подбор по названию или категории
    if (strpos($category, 'телефон') !== false || strpos($category, 'электрон') !== false) {
        $selected_dna = "tech_apple";
    } elseif (strpos($sub_category, 'еда') !== false || strpos($category, 'сладости') !== false) {
        $selected_dna = "fmcg_explosive";
    } elseif (strpos($sub_category, 'напитки') !== false || strpos($sub_category, 'вода') !== false) {
        $selected_dna = "beverage_fresh";
    } elseif (strpos($category, 'спорт') !== false || strpos($category, 'туризм') !== false) {
        $selected_dna = "outdoor_steel";
    } elseif (strpos($category, 'красота') !== false || strpos($category, 'парфюм') !== false) {
        $selected_dna = "beauty_luxury";
    }
}

$core_style = $dna_prompts[$selected_dna];

// ==============================================================================
// 🛠 СБОРКА ФИНАЛЬНОГО ПРОМПТА
// ==============================================================================
$prompt = "$core_style " . 
          "CRITICAL INSTRUCTION: The main object from the reference image MUST remain EXACTLY the same (same shape, color, branding). Do not alter the product. Build the infographic layout around and behind it. " .
          "TYPOGRAPHY INSTRUCTION: Write EXACTLY this headline: \"$headline\". " .
          "Write these features EXACTLY as provided: \"$features_text\". " .
          "IMPORTANT: Keep the exact original language (Russian, Turkmen, or English). DO NOT translate the text. Render the characters exactly as written. Ensure typography is perfectly legible. 8K resolution, masterpiece.";

file_put_contents($log_file, "🎨 Промпт ($selected_dna): $prompt\n", FILE_APPEND);

// ==============================================================================
// ВЫЗОВ НЕЙРОСЕТИ (ГЕНЕРИРУЕМ 3 ВАРИАНТА В ЦИКЛЕ)
// ==============================================================================
$api_key = "AQ.Ab8RN6LFNus6fYNVeGEXf852wLISQpBMTkpEcyCsb3RkYSdUsA";
$flash_url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-image:generateContent?key=" . trim($api_key);

$local_image_path = str_replace("https://ldr.com.tm/api/v1/", __DIR__ . "/", $image_url);
$img_data = @file_get_contents($local_image_path);

if (!$img_data) {
    fail_and_refund($conn, $task_id, $user_id, $cost, $log_file, "Failed to load transparent source image");
    exit();
}

$base64_image = base64_encode($img_data);
$mime_type = mime_content_type($local_image_path) ?: "image/png";

$generated_urls = [];

// Делаем 3 запроса к ИИ
for ($i = 1; $i <= 3; $i++) {
    $variant_instruction = "";
    
   if ($i == 1) {
        $variant_instruction = "VARIANT 1: For the features at the bottom, use the provided text ('$features_text') but rephrase them slightly to sound ultra-premium and focused on QUALITY.";
    } elseif ($i == 2) {
        $variant_instruction = "VARIANT 2: For the features, invent 3 completely NEW and creative marketing features focused on PERFORMANCE and LIFESTYLE. Do not repeat the exact provided text.";
    } else {
        $variant_instruction = "VARIANT 3: For the features, mix the provided text with 2 brand-new, powerful, emotionally engaging benefits. Use a slightly different background lighting.";
    }

    // Жесткий приказ: НИКАКИХ ЛОГОТИПОВ!
    $variant_prompt = $prompt . " " . $variant_instruction . " DO NOT TRANSLATE. Use the original language. CRITICAL: ABSOLUTELY NO LOGOS, NO WATERMARKS, AND NO BRAND ICONS ALLOWED IN THE GENERATION. Only draw the product and the requested typography.";
    
    $payload = [
        "contents" => [[
            "parts" => [
                ["text" => $variant_prompt],
                ["inlineData" => ["mimeType" => $mime_type, "data" => $base64_image]]
            ]
        ]]
    ];

    $ch = curl_init($flash_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 90);

    $resp = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($resp, true);
    $b64_result = null;

    if (isset($data['candidates'][0]['content']['parts'])) {
        foreach ($data['candidates'][0]['content']['parts'] as $part) {
            if (isset($part['inlineData']['data'])) { $b64_result = $part['inlineData']['data']; break; }
            elseif (isset($part['inline_data']['data'])) { $b64_result = $part['inline_data']['data']; break; }
        }
    }

    if ($b64_result) {
        $new_filename = "info_res_" . time() . "_" . rand(1000, 9999) . "_v$i.jpg";
        $new_filepath = __DIR__ . "/uploads/ai_originals/" . $new_filename;
        file_put_contents($new_filepath, base64_decode($b64_result));
        $generated_urls[] = "https://ldr.com.tm/api/v1/uploads/ai_originals/" . $new_filename;
        file_put_contents($log_file, "✅ Вариант $i успешно сгенерирован.\n", FILE_APPEND);
    }
}

// ==============================================================================
// ЗАВЕРШЕНИЕ: ЗАПИСЬ МАССИВА КАРТИНОК ИЛИ ОТМЕНА
// ==============================================================================
if (count($generated_urls) > 0) {
    // Сохраняем JSON массив ссылок в БД!
    $json_urls = json_encode($generated_urls, JSON_UNESCAPED_SLASHES);
    
    $stmt = $conn->prepare("UPDATE ai_tasks SET status = 'completed', result_image_url = ? WHERE task_id = ?");
    $stmt->bind_param("ss", $json_urls, $task_id); 
    $stmt->execute();
    $stmt->close();
    file_put_contents($log_file, "🎉 Инфографика завершена. Сохранено " . count($generated_urls) . " вариантов.\n", FILE_APPEND);
} else {
    fail_and_refund($conn, $task_id, $user_id, $cost, $log_file, "AI failed to generate any images");
}

$conn->close();

function fail_and_refund($conn, $task_id, $user_id, $cost, $log_file, $error_msg) {
    file_put_contents($log_file, "💀 ОШИБКА: $error_msg. Возврат $cost TMT.\n", FILE_APPEND);
    $conn->query("UPDATE users SET balance = balance + $cost WHERE id = '$user_id'");
    
    $refund_msg = "Генерация инфографики не удалась. Средства ($cost TMT) возвращены на ваш баланс.";
    $sysAvatar = "https://cdn-icons-png.flaticon.com/512/2040/2040946.png";
    $conn->query("INSERT INTO notifications (user_id, sender_id, type, action_id, title, message, user_avatar, created_at, is_read) VALUES ('$user_id', 'SYSTEM', 'system', 'ai_infographic', 'Возврат средств 💰', '$refund_msg', '$sysAvatar', NOW(), 0)");
    
    $conn->query("UPDATE ai_tasks SET status = 'failed', error_message = 'Generation failed' WHERE task_id = '$task_id'");
}
?>
