>'chatbot'))::int as bots_count, COALESCE(ROUND(AVG((experience->>'total_ms')::int))::int, 0) as avg_ms FROM ai_learning_log WHERE learned_at > NOW() - interval '24 hours'"); $summary = pg_fetch_assoc($r); $summary['success_pct'] = $summary['total_learned'] > 0 ? round(100.0 * $summary['success_total'] / $summary['total_learned']) : 0; // Conversations count $r = pg_query($pg, "SELECT COUNT(*)::int as total, COUNT(DISTINCT session_id)::int as sessions FROM wevia_conversations"); $c = pg_fetch_assoc($r); $summary['conversations'] = (int)$c['total']; $summary['sessions'] = (int)$c['sessions']; // Per chatbot (24h) $r = pg_query($pg, "SELECT experience->>'chatbot' as chatbot, COUNT(*)::int as total, SUM(CASE WHEN outcome_success THEN 1 ELSE 0 END)::int as success FROM ai_learning_log WHERE learned_at > NOW() - interval '24 hours' AND experience->>'chatbot' IS NOT NULL GROUP BY experience->>'chatbot' ORDER BY total DESC"); $chatbots = []; while ($row = pg_fetch_assoc($r)) { $row['total'] = (int)$row['total']; $row['success'] = (int)$row['success']; $row['success_pct'] = $row['total'] > 0 ? round(100.0 * $row['success'] / $row['total']) : 0; $chatbots[] = $row; } // Intents distribution $r = pg_query($pg, "SELECT experience->>'intent' as intent, COUNT(*)::int as count, SUM(CASE WHEN outcome_success THEN 1 ELSE 0 END)::int as success FROM ai_learning_log WHERE learned_at > NOW() - interval '24 hours' GROUP BY experience->>'intent' ORDER BY count DESC"); $intents = []; while ($row = pg_fetch_assoc($r)) { $row['count'] = (int)$row['count']; $row['success'] = (int)$row['success']; $row['rate'] = $row['count'] > 0 ? round(100.0 * $row['success'] / $row['count']) : 0; $intents[] = $row; } // Latest 10 $r = pg_query($pg, "SELECT learned_at, experience->>'chatbot' as chatbot, experience->>'intent' as intent, outcome_success as outcome FROM ai_learning_log ORDER BY learned_at DESC LIMIT 10"); $latest = []; while ($row = pg_fetch_assoc($r)) { $row['outcome'] = $row['outcome'] === 't'; $latest[] = $row; } pg_close($pg); echo json_encode([ 'ts' => date('c'), 'window' => '24h', 'summary' => $summary, 'chatbots' => $chatbots, 'intents' => $intents, 'latest' => $latest, ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } catch (Throwable $e) { http_response_code(500); echo json_encode(['error' => $e->getMessage()]); }