import { useEffect, useState, useRef } from 'react'; import { io, Socket } from 'socket.io-client'; import { Download, Sparkles, Play, Pause, Terminal } from 'lucide-react'; import type { LogService } from '../types'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { cn } from '@/lib/utils'; export default function LogTerminal({ service, initialLogs = [] }: { service: LogService, initialLogs?: { id: string, line: string, isError: boolean }[] }) { const [logs, setLogs] = useState<{ id: string, line: string, isError: boolean }[]>(initialLogs); const [isPaused, setIsPaused] = useState(false); const isPausedRef = useRef(false); const pendingLogsRef = useRef<{ id: string, line: string, isError: boolean }[]>([]); const socketRef = useRef(null); useEffect(() => { isPausedRef.current = isPaused; }, [isPaused]); useEffect(() => { if (!socketRef.current) { socketRef.current = io(`${import.meta.env.VITE_API_URL || 'http://localhost:3001'}`, { withCredentials: true }); } setLogs(initialLogs); pendingLogsRef.current = []; const handleLogLine = (data: { serviceId: number | string, line: string }) => { if (data.serviceId === service.id) { const isError = service.alertKeyword ? data.line.includes(service.alertKeyword) : (data.line.includes('ERROR') || data.line.includes('Exception')); const newLog = { id: Date.now() + Math.random().toString(), line: data.line, isError }; if (!isPausedRef.current) { setLogs(prev => [...prev, newLog].slice(-300)); } else { pendingLogsRef.current = [...pendingLogsRef.current, newLog].slice(-300); } } }; socketRef.current.on('logLine', handleLogLine); return () => { socketRef.current?.off('logLine', handleLogLine); }; }, [service.id]); const terminalContentRef = useRef(null); const togglePause = () => { if (isPaused) { setLogs(prev => [...prev, ...pendingLogsRef.current].slice(-300)); pendingLogsRef.current = []; } setIsPaused(!isPaused); }; useEffect(() => { if (!isPaused && terminalContentRef.current) { terminalContentRef.current.scrollTop = terminalContentRef.current.scrollHeight; } }, [logs, isPaused]); const handleExport = () => { if (logs.length === 0) return; const csvContent = [ "ID,Status,Log Line", ...logs.map(log => `${log.id},${log.isError ? 'ERROR' : 'INFO'},"${log.line.replace(/"/g, '""')}"`) ].join("\n"); const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' }); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.setAttribute("href", url); link.setAttribute("download", `logs_${service.name}_${new Date().toISOString().slice(0, 10)}.csv`); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); }; const handleAnalyzeLog = (line: string) => { window.dispatchEvent(new CustomEvent('analyze-log', { detail: { line, serviceName: service.name } })); }; const handleAnalyzeChunk = (chunk: { id: string, line: string, isError: boolean }[]) => { if (chunk.length === 0) return; const batchText = chunk.map(l => l.line).join('\n'); window.dispatchEvent(new CustomEvent('analyze-log', { detail: { line: `Voici un ensemble de ${chunk.length} logs :\n${batchText}`, serviceName: service.name } })); }; const handleGlobalCheckup = () => { if (logs.length === 0) return; const MAX_CHARS = 6000; let batchText = ""; let truncated = false; let includedCount = 0; for (let i = logs.length - 1; i >= 0; i--) { const lineWithBreak = logs[i].line + '\n'; if (batchText.length + lineWithBreak.length > MAX_CHARS) { truncated = true; break; } batchText = lineWithBreak + batchText; includedCount++; } const message = truncated ? `### 📊 Diagnostic complet demandé\n\n*Analyse des ${includedCount} logs les plus récents...*\n\n
\nVoir les logs transmis à l'IA\n\n\`\`\`\n${batchText}\n\`\`\`\n
` : `### 📊 Diagnostic complet demandé\n\n*Analyse de l'intégralité des logs (${includedCount})...*\n\n
\nVoir les logs transmis à l'IA\n\n\`\`\`\n${batchText}\n\`\`\`\n
`; window.dispatchEvent(new CustomEvent('analyze-log', { detail: { line: message, serviceName: service.name } })); }; const chunkedLogs = []; for (let i = logs.length; i > 0; i -= 5) { const start = Math.max(0, i - 5); chunkedLogs.unshift(logs.slice(start, i)); } return (
{/* Terminal Toolbar */}
{isPaused ? 'TERMINAL PAUSÉ' : 'FLUX EN DIRECT'}
{/* Terminal View */}
{chunkedLogs.length === 0 ? (

Initialisation de la sortie standard...

) : ( chunkedLogs.map((chunk, chunkIndex) => (
{chunk.map(log => (
{log.line}
))}
{/* Chunk Sidebar */}
handleAnalyzeChunk(chunk)} title="Analyser ce bloc de logs" >
)) )}
); }