<?php
/**
 * api/router.php - EXPERT TRAFFIC CONTROLLER (REVISED)
 * Fitur: Instant 429 Ban, Strict Panic Mode, Smart Queue.
 */

function getBestKey($provider, $conn, $cfg_row) {
    // 1. AUTO HEALING: Bebaskan tahanan yang masa hukumannya habis
    // [OPTIMASI] Tambahkan index pada kolom (provider, status, cooldown_until) di database agar query ini kilat.
    mysqli_query($conn, "UPDATE api_health_monitor 
                         SET status = 'ready', cooldown_until = NULL, fail_count = 0 
                         WHERE provider = '$provider' 
                         AND status = 'cooldown' 
                         AND cooldown_until <= NOW()");

    // 2. STRATEGI LRU (Least Recently Used)
    // Ambil kunci yang READY dan paling lama istirahat
    $q = mysqli_query($conn, "SELECT slot_id FROM api_health_monitor 
                              WHERE provider = '$provider' AND status = 'ready' 
                              ORDER BY last_used ASC LIMIT 1");
    
    $slot = mysqli_fetch_assoc($q);

    // 3. STRICT PANIC MODE (Revisi Expert)
    // JANGAN ambil kunci yang sedang cooldown. Itu bunuh diri.
    // Jika $slot kosong (semua key mati/cooldown), return NULL.
    // Biarkan gemini.php pindah ke Groq/Backup.
    
    if ($slot) {
        $slot_name = $slot['slot_id'];
        // Kunci langsung ditandai "baru dipakai" detik ini juga
        // agar request concurrent lain tidak mengambil kunci yang sama
        mysqli_query($conn, "UPDATE api_health_monitor SET last_used = NOW() WHERE slot_id = '$slot_name'");
        
        // Cek apakah config key ada isinya
        if (empty($cfg_row[$slot_name])) {
             return null; // Safety check jika DB ada tapi Config kosong
        }

        return ['key' => $cfg_row[$slot_name], 'slot' => $slot_name];
    }
    
    // Semua kunci habis/sedang dihukum -> Failover Triggered
    return null; 
}

function reportTrafficStatus($slot_id, $is_success, $http_code, $conn) {
    if ($is_success) {
        // SUKSES: Reset dosa jadi suci kembali
        mysqli_query($conn, "UPDATE api_health_monitor 
                             SET status = 'ready', fail_count = 0, cooldown_until = NULL 
                             WHERE slot_id = '$slot_id'");
    } else {
        // GAGAL - ANALISA PENYEBAB
        
        // A. Dosa Besar (Key Invalid/Expired) -> Matikan Permanen
        if ($http_code == 400 || $http_code == 403) {
            mysqli_query($conn, "UPDATE api_health_monitor SET status = 'suspended', fail_count = 999 WHERE slot_id = '$slot_id'");
            return;
        }

        // B. Rate Limit (429) -> HUKUM LANGSUNG (Revisi Expert)
        // Jangan beri toleransi 3 kali. Google tidak suka ditawar.
        if ($http_code == 429) {
            $hukuman_detik = 60; // 1 Menit penjara
            mysqli_query($conn, "UPDATE api_health_monitor 
                                 SET status = 'cooldown', 
                                     fail_count = fail_count + 1,
                                     cooldown_until = DATE_ADD(NOW(), INTERVAL $hukuman_detik SECOND)
                                 WHERE slot_id = '$slot_id'");
            return; // Selesai, jangan lanjut ke logic fail_count
        }

        // C. Koneksi Gagal / Timeout (500, 503, 0) -> Masih boleh dimaafkan (Toleransi 3x)
        $cek = mysqli_query($conn, "SELECT fail_count FROM api_health_monitor WHERE slot_id='$slot_id'");
        $d = mysqli_fetch_assoc($cek);
        $current_fail = ($d['fail_count'] ?? 0) + 1;

        if ($current_fail < 3) {
            // Peringatan SP1 / SP2
            mysqli_query($conn, "UPDATE api_health_monitor SET fail_count = $current_fail WHERE slot_id = '$slot_id'");
        } else {
            // SP3 -> Penjara sebentar (Fast Recovery)
            // Error server biasanya pulih cepat, cukup 15 detik
            mysqli_query($conn, "UPDATE api_health_monitor 
                                 SET status = 'cooldown', 
                                     fail_count = $current_fail,
                                     cooldown_until = DATE_ADD(NOW(), INTERVAL 15 SECOND)
                                 WHERE slot_id = '$slot_id'");
        }
    }
}
?>