<?php
// scan_kategori_bulan_ini.php
// Script untuk menscan ulang berita di bulan ini yang berkategori "Lainnya"
require_once 'db.php';

header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-cache');
set_time_limit(0); // Biarkan berjalan sampai selesai

// Matikan output buffering agar bisa streaming di browser
@ini_set('zlib.output_compression', 0);
@ini_set('implicit_flush', 1);
for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
ob_implicit_flush(1);

// Padding awal agar browser tidak buffer (khusus browser turunan Chrome/Safari)
echo str_pad("", 4096, " ");
echo "<pre style='font-family: monospace; background: #000; color: #0f0; padding: 20px; font-size: 14px; white-space: pre-wrap;'>\n";

function log_out($msg) {
    echo $msg . "\n";
    @ob_flush();
    @flush();
}

log_out("=== MEMULAI SCAN ULANG KATEGORI 'LAINNYA' BULAN INI ===");
log_out("Waktu mulai: " . date('Y-m-d H:i:s') . "\n");

$bulan_ini = date('m');
$tahun_ini = date('Y');

// Ambil instansi aktif
$stmt_instansi = $pdo->query("SELECT * FROM instansi WHERE status = 'aktif'");
$instansis = $stmt_instansi->fetchAll(PDO::FETCH_ASSOC);

foreach ($instansis as $instansi) {
    $instansi_id = $instansi['id'];
    log_out("Memproses Instansi: " . $instansi['nama_instansi'] . " (ID: $instansi_id)");
    
    $api_key = trim($instansi['api_key_ai']);
    $ai_agent = trim($instansi['ai_agent'] ?? 'Groq');
    $ai_model = trim($instansi['ai_model'] ?? 'llama3-70b-8192');
    $keywords_raw = trim($instansi['keyword_global']);
    $demoted_raw = trim($instansi['demoted_keywords'] ?? '');

    if (empty($api_key)) {
        log_out(" -> Skip: API Key belum diatur.\n");
        continue;
    }

    // Ambil keyword entities untuk prompt
    $stmt_entities = $pdo->prepare("SELECT entity, type FROM instansi_entities WHERE instansi_id = ?");
    $stmt_entities->execute([$instansi_id]);
    $entities = $stmt_entities->fetchAll(PDO::FETCH_ASSOC);
    
    $target_kws = [];
    $conflict_kws = [];
    foreach($entities as $e) {
        if ($e['type'] === 'target') $target_kws[] = $e['entity'];
        if ($e['type'] === 'conflict') $conflict_kws[] = $e['entity'];
    }
    
    $keywords_str = !empty($target_kws) ? implode(', ', $target_kws) : $keywords_raw;
    $conflict_str = implode(', ', $conflict_kws);

    // Ambil berita bulan ini yang kategorinya 'Lainnya' (Atau NULL/kosong)
    $stmt_berita = $pdo->prepare("SELECT id, judul, cuplikan FROM berita WHERE instansi_id = ? AND MONTH(tanggal) = ? AND YEAR(tanggal) = ? AND (kategori_berita = 'Lainnya' OR kategori_berita IS NULL OR kategori_berita = '')");
    $stmt_berita->execute([$instansi_id, $bulan_ini, $tahun_ini]);
    $berita_list = $stmt_berita->fetchAll(PDO::FETCH_ASSOC);

    if (empty($berita_list)) {
        log_out(" -> Tidak ada berita kategori 'Lainnya' di bulan ini.\n");
        continue;
    }

    log_out(" -> Menemukan " . count($berita_list) . " berita untuk dipindai ulang.");

    $updated = 0;
    foreach ($berita_list as $b) {
        $judul = $b['judul'];
        $cuplikan = $b['cuplikan'];
        
        $system_prompt = "
AI monitoring berita instansi.
Target: {$keywords_str}
Aturan relevansi:
- Fokus utama harus membahas target.
- Banjar != Banjarbaru != Banjarmasin.
";
        if (!empty($conflict_kws)) {
            $system_prompt .= "\n- Jika fokus berita pada entitas konflik [{$conflict_str}] maka relevansi=TIDAK.";
        }
        if (!empty($demoted_raw)) {
            $system_prompt .= "\n- Jika fokus utama pada [{$demoted_raw}] maka relevansi=TIDAK.";
        }
        $system_prompt .= "
Kategori:
Infrastruktur
Pelayanan
Pendidikan
Kesehatan
Sosial
Keamanan
Politik
Lingkungan
Ekonomi
Lainnya
Rule:
- polisi/kriminal/narkoba/pencurian/pembunuhan=Keamanan
- jalan/jembatan/banjir=Infrastruktur
- rumah sakit/BPJS/puskesmas=Kesehatan
- sekolah/guru/siswa=Pendidikan
Tentukan:
- relevansi
- sentimen
- urgensi
- kategori
Balas JSON saja:
{
\"r\":\"YA/TIDAK\",
\"s\":\"POSITIF/NEGATIF/NETRAL\",
\"u\":\"TINGGI/SEDANG/RENDAH\",
\"k\":Sesuai list Kategori 
}
";

        $user_prompt = $judul . "\n" . mb_substr(strip_tags($cuplikan), 0, 300);

        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $api_key
        ];

        $data = [
            "model" => (!empty($ai_model) ? $ai_model : 'llama3-70b-8192'),
            "messages" => [
                ["role" => "system", "content" => $system_prompt], 
                ["role" => "user", "content" => $user_prompt]
            ],
            "temperature" => 0.2
        ];

        $json_payload = json_encode($data, JSON_INVALID_UTF8_SUBSTITUTE | JSON_UNESCAPED_UNICODE);
        if ($json_payload === false) {
            log_out("   [ERROR] ID {$b['id']}: Gagal menyusun request JSON (Invalid UTF-8). Error: " . json_last_error_msg());
            continue;
        }

        $api_url = "https://api.groq.com/openai/v1/chat/completions";
        if ($ai_agent === 'KoboiLLM') {
            $api_url = "https://api.koboillm.com/v1/chat/completions";
        }

        $ch_ai = curl_init($api_url);
        curl_setopt($ch_ai, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch_ai, CURLOPT_POST, true);
        curl_setopt($ch_ai, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch_ai, CURLOPT_POSTFIELDS, $json_payload);
        curl_setopt($ch_ai, CURLOPT_TIMEOUT, 20);
        curl_setopt($ch_ai, CURLOPT_SSL_VERIFYPEER, false);
        
        $ai_response = curl_exec($ch_ai);
        curl_close($ch_ai);

        if ($ai_response) {
            $res_json = json_decode($ai_response, true);
            $raw_ai = $res_json['choices'][0]['message']['content'] ?? '';
            
            if (empty($raw_ai) && isset($res_json['error'])) {
                log_out("   [ERROR] ID {$b['id']}: API AI Error -> " . json_encode($res_json['error']));
            } else if (preg_match('/\{[\s\S]*\}/', str_replace(['```json', '```'], '', $raw_ai), $matches)) {
                $hasil_ai = json_decode($matches[0], true);
                if ($hasil_ai && isset($hasil_ai['k'])) {
                    $kategori_baru = trim($hasil_ai['k']);
                    $sentimen_ai = strtolower(trim($hasil_ai['s'] ?? 'netral'));
                    $urgensi_ai = strtolower(trim($hasil_ai['u'] ?? 'rendah'));
                    
                    $sentimen_db = $sentimen_ai;
                    if ($sentimen_ai === 'positif') $sentimen_db = 'baik';
                    if ($sentimen_ai === 'negatif') $sentimen_db = 'buruk';

                    if ($kategori_baru !== 'Lainnya' && !empty($kategori_baru)) {
                        $stmt_update = $pdo->prepare("UPDATE berita SET kategori_berita = ?, sentimen = ?, urgensi = ? WHERE id = ?");
                        $stmt_update->execute([$kategori_baru, $sentimen_db, $urgensi_ai, $b['id']]);
                        log_out("   [OK] ID {$b['id']}: 'Lainnya' -> '$kategori_baru' (Sentimen: $sentimen_db)");
                        $updated++;
                    } else {
                        log_out("   [SKIP] ID {$b['id']} tetap '$kategori_baru'.");
                    }
                } else {
                    log_out("   [ERROR] ID {$b['id']}: Gagal parse JSON. Error: " . json_last_error_msg() . " | Raw: " . trim($matches[0]));
                }
            } else {
                log_out("   [ERROR] ID {$b['id']}: AI tidak mengembalikan format JSON yang valid. Raw AI Output: " . trim($raw_ai));
            }
        } else {
            log_out("   [ERROR] ID {$b['id']}: Gagal koneksi ke API AI.");
        }
        
        // Jeda 3 detik untuk menghindari rate limit API Groq
        sleep(6);
    }
    
    log_out(" -> Selesai memproses instansi. Total diupdate: $updated\n");
}

log_out("=== PROSES SCAN ULANG SELESAI ===");
echo "</pre>\n";
?>
