<?php

require_once __DIR__ . '/client-config.php';

$dir = __DIR__ . '/fallback_events';
$files = glob($dir . '/*.jsonl');

if (empty($files)) {
    echo "Nenhum arquivo de eventos encontrado.\n";
    exit(0);
}

$totalSent = 0;
$totalFailed = 0;

foreach ($files as $file) {
    echo "Processando: " . basename($file) . "\n";
    
    $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $sentEvents = [];
    
    foreach ($lines as $i => $line) {
        $event = json_decode($line, true);
        if (!$event || !isset($event['payload'])) {
            echo "  - Linha " . ($i+1) . ": formato inválido\n";
            continue;
        }
        
        $payload = $event['payload'];
        
        
        $url = ADMIN_SERVER_URL . '/api/v1/index.php?action=track';
        
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'X-API-Key: ' . SITE_API_KEY,
            ],
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode >= 200 && $httpCode < 300) {
            $sentEvents[] = $i;
            $totalSent++;
            echo ".";
        } else {
            $totalFailed++;
            echo "X";
        }
        
        
        usleep(50000); 
    }
    
    echo "\n  - Enviados: " . count($sentEvents) . "/" . count($lines) . "\n";
    
    
    if (count($sentEvents) === count($lines)) {
        $processedDir = $dir . '/processed';
        if (!is_dir($processedDir)) {
            mkdir($processedDir, 0755, true);
        }
        rename($file, $processedDir . '/' . basename($file));
        echo "  - Arquivo movido para processed/\n";
    }
}

echo "\n=== RESUMO ===\n";
echo "Total enviados: {$totalSent}\n";
echo "Total falharam: {$totalFailed}\n";
