<?php
// =========================================================================
// llm/api/koneksi_gemini.php - KONEKSI HTTP CLIENT KE INTERNAL LLM SIKA AI
// Developer: Sikawarsito, S.Kom
// Fungsi: Menjembatani request dari frontend api/gemini.php untuk ditembak
//         langsung ke endpoint pusat bot_api.php secara HTTP agar 
//         memanfaatkan Fuzzy Cache & Anti-DDoS tanpa Race Condition.
// =========================================================================

function getMasterKey($conn) {
    // Mengambil API Key pertama yang aktif di database (biasanya milik Admin Utama)
    $res = mysqli_query($conn, "SELECT api_key FROM api_key_bot WHERE status = 'active' ORDER BY id ASC LIMIT 1");
    if ($res && mysqli_num_rows($res) > 0) {
        $row = mysqli_fetch_assoc($res);
        return $row['api_key'];
    }
    return null;
}

function executeInternalLLM($full_prompt, $file_part, $temp, $conn, $cfg, $model, $sys_prompt, $user_input, $hist_ctx) {
    // Pastikan master token tersedia
    $master_token = getMasterKey($conn);
    if (!$master_token) {
        return "ERROR: Tidak ada API Key aktif (Master Token) di dalam sistem untuk menembak LLM internal.";
    }

    // Bangun URL bot_api.php secara DINAMIS agar berjalan di LOKAL maupun HOSTING
    // Dengan membaca path file aktual relatif terhadap DOCUMENT_ROOT server
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'];
    $doc_root       = rtrim(str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']), '/');
    $bot_api_real   = str_replace('\\', '/', realpath(__DIR__ . '/bot_api.php'));
    $bot_api_webpath = str_replace($doc_root, '', $bot_api_real); // misal: /llm/api/bot_api.php atau /xieqa/llm/api/bot_api.php
    $bot_api_url    = $scheme . '://' . $host . $bot_api_webpath;

    // Siapkan Payload. 
    // Siapkan Payload. 
    // Meneruskan file_part agar fitur Vision/Image dapat diproses oleh bot_api.php
    $payload = [
        "pesan" => $full_prompt,
        "file_part" => $file_part
    ];

    $ch = curl_init($bot_api_url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "Authorization: Bearer " . $master_token,
        "Content-Type: application/json",
        "X-Xieqa-Internal: SikaWarsito2026BypassLimit"
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload, JSON_INVALID_UTF8_SUBSTITUTE));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Timeout dibuat ektra panjang untuk menunggu penalaran AI yang butuh waktu lama saat generate Dokumen
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 600); 

    $res = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($http_code == 200) {
        $data = json_decode($res, true);
        
        // Memeriksa format kembalian standar dari bot_api.php (OpenAI Format)
        if (isset($data['status']) && $data['status'] === 'success') {
            if (isset($data['choices'][0]['message']['content'])) {
                return $data['choices'][0]['message']['content'];
            }
        }
        
        // Jika bot_api.php merespon limit atau sibuk
        if (isset($data['status']) && ($data['status'] === 'error' || $data['status'] === 'busy')) {
            return "ERROR_JSON:" . json_encode($data);
        }
    } else if ($http_code == 429) {
        $err = json_decode($res, true);
        return "Sistem mendeteksi akses terlalu padat. " . ($err['message'] ?? "Harap tunggu antrian.");
    } else if ($http_code == 401 || $http_code == 403) {
        return "Akses internal LLM ditolak. Master API Key tidak valid atau dibekukan.";
    }

    return "FAIL (HTTP: " . $http_code . " | Response: " . substr(strip_tags($res), 0, 150) . ")";
}
?>
