date('c'), 'session' => $in['session'] ?? 'anon', 'user' => $in['user'] ?? 'yacine', 'type' => $in['type'] ?? 'chat', 'intent' => $in['intent'] ?? null, 'provider' => $in['provider'] ?? null, 'message' => substr((string)($in['message'] ?? ''), 0, 500), 'response' => substr((string)($in['response'] ?? ''), 0, 1000), 'ms' => $in['ms'] ?? null, 'status' => $in['status'] ?? 'ok', ]; $line = json_encode($event, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) . "\n"; @file_put_contents($LOG, $line, FILE_APPEND | LOCK_EX); // Trim if needed if (file_exists($LOG) && filesize($LOG) > 8 * 1024 * 1024) { // > 8MB $lines = @file($LOG, FILE_IGNORE_NEW_LINES); if ($lines && count($lines) > $MAX_LINES) { $lines = array_slice($lines, -$MAX_LINES); @file_put_contents($LOG, implode("\n", $lines) . "\n"); } } http_response_code(200); echo json_encode(['ok' => true, 'logged' => $event]); exit; } // GET: retrieve events $limit = max(1, min((int)($_GET['limit'] ?? 50), 500)); $session = $_GET['session'] ?? ''; $intent = $_GET['intent'] ?? ''; $type = $_GET['type'] ?? ''; if (!file_exists($LOG)) { echo json_encode(['events' => [], 'total' => 0]); exit; } $lines = @file($LOG, FILE_IGNORE_NEW_LINES) ?: []; $events = []; foreach (array_reverse($lines) as $line) { $e = @json_decode($line, true); if (!is_array($e)) continue; if ($session && ($e['session'] ?? '') !== $session) continue; if ($intent && ($e['intent'] ?? '') !== $intent) continue; if ($type && ($e['type'] ?? '') !== $type) continue; $events[] = $e; if (count($events) >= $limit) break; } // Also stats $stats = ['total_lines' => count($lines), 'returned' => count($events)]; $intents_seen = []; foreach (array_slice($lines, -200) as $line) { $e = @json_decode($line, true); if (!is_array($e)) continue; $int = $e['intent'] ?? '?'; $intents_seen[$int] = ($intents_seen[$int] ?? 0) + 1; } arsort($intents_seen); $stats['top_intents_last_200'] = array_slice($intents_seen, 0, 10); echo json_encode(['events' => $events, 'stats' => $stats], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);