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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import React, { useState, useEffect, useCallback } from 'react';
import { useAuth, api } from '@nexus/shared';
import { 
  Activity, Database, Brain, Clock, 
  AlertCircle, RefreshCcw, 
  Cpu, Workflow, Shield, Search, Zap, Layout,
  ChevronLeft, ChevronRight
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import styles from './InfraMonitor.module.css';

interface HealthNode {
  status: 'UP' | 'DOWN' | 'DEGRADED';
  latency_ms: number;
  pending_jobs?: number;
}

interface SystemStatus {
  database: HealthNode;
  redis: HealthNode;
  ollama: HealthNode;
  timestamp: string;
}

interface InfraHistory {
  DATABASE: number[];
  REDIS: number[];
  OLLAMA: number[];
}

interface WorkflowStep {
  name: string;
  status: 'success' | 'error' | 'pending' | 'skipped';
  timestamp: string;
}

interface AIWorkflow {
  id: string;
  entity_id: string;
  workflow_type: string;
  current_stage: string;
  steps: WorkflowStep[];
  total_duration_ms: number;
}

interface AIInteraction {
  id: string;
  ticket_id: string | null;
  agent_name: string;
  status: string;
  output_data: any;
  duration_ms?: any;
  created_at: string;
}

const getAgentIcon = (name: string) => {
  const n = name.toLowerCase();
  if (n.includes('triage')) return <Shield size={18} />;
  if (n.includes('suggestion')) return <Zap size={18} />;
  if (n.includes('remediation')) return <Cpu size={18} />;
  if (n.includes('search')) return <Search size={18} />;
  return <Brain size={18} />;
};

const Sparkline = ({ data, color, loading }: { data: number[], color: string, loading: boolean }) => {
  if (loading || data.length === 0) return <div style={{ height: 40 }} />;
  
  // Safeguard: Ensure we have at least 2 points to draw a line, 
  // or handle the single point case by duplicating it.
  const chartData = data.length === 1 ? [data[0], data[0]] : data;

  const min = Math.min(...chartData);
  const max = Math.max(...chartData);
  const range = max - min || 1;
  const width = 200;
  const height = 40;
  
  const points = chartData.map((val, i) => {
    const x = (i / (chartData.length - 1)) * width;
    const y = height - ((val - min) / range) * height;
    // Final NaN safeguard
    return `${isNaN(x) ? 0 : x},${isNaN(y) ? height : y}`;
  }).join(' ');

  const areaPoints = `${points} ${width},${height} 0,${height}`;

  return (
    <div className={styles.sparklineContainer}>
      <svg width="100%" height={height} viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none">
        <defs>
          <linearGradient id={`grad-${color}`} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.4" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        <motion.path
          d={`M ${points}`}
          fill="none"
          stroke={color}
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
          initial={{ pathLength: 0 }}
          animate={{ pathLength: 1 }}
          transition={{ duration: 1.5, ease: "easeInOut" }}
        />
        <motion.polygon
          points={areaPoints}
          fill={`url(#grad-${color})`}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.5, duration: 1 }}
        />
      </svg>
    </div>
  );
};

const StatusCard = ({ title, node, history, icon: Icon, color, loading }: { 
  title: string, 
  node: HealthNode | undefined, 
  history: number[],
  icon: any, 
  color: string,
  loading: boolean
}) => (
  <div className={styles.card}>
    <div className={styles.cardTopBorder} style={{ background: color }} />
    {loading && <div className={styles.shimmerOverlay} />}
    
    <div className={`${styles.cardHeader} ${loading ? styles.fading : ''}`}>
      <div className={styles.cardTitle}>
        <Icon size={18} color={color} strokeWidth={2.5} />
        {title}
      </div>
      <div className={`${styles.statusOrb} ${node?.status || 'DOWN'}`} />
    </div>
    
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
      <div>
        <div className={`${styles.statValue} ${loading ? styles.fading : ''}`}>
          {node?.status === 'UP' ? `${node.latency_ms.toFixed(1)}` : '---'}
          {node?.status === 'UP' && <span style={{ fontSize: '1rem', marginLeft: '4px', opacity: 0.6 }}>ms</span>}
        </div>
        <div className={styles.statLabel}>Avg Latency</div>
      </div>
      
      <div style={{ width: '40%', marginBottom: '10px' }}>
         <Sparkline data={history} color={color} loading={loading} />
      </div>
    </div>

    <div className={`${styles.metrics} ${loading ? styles.fading : ''}`}>
      {node?.pending_jobs !== undefined && (
        <div className={styles.metricItem}>
          <div className={styles.metricLabel}>Process Queue</div>
          <div className={styles.metricValue}>{node.pending_jobs}</div>
        </div>
      )}
      <div className={styles.metricItem}>
        <div className={styles.metricLabel}>Protocol</div>
        <div className={styles.metricValue}>TLS 1.3</div>
      </div>
    </div>
  </div>
);

const PAGE_SIZE = 6;

const InfraMonitor: React.FC = () => {
  useAuth();
  const [status, setStatus] = useState<SystemStatus | null>(null);
  const [history, setHistory] = useState<InfraHistory>({ DATABASE: [], REDIS: [], OLLAMA: [] });
  const [workflows, setWorkflows] = useState<AIWorkflow[]>([]);
  const [interactions, setInteractions] = useState<AIInteraction[]>([]);
  const [loading, setLoading] = useState(true);
  const [lastRefreshed, setLastRefreshed] = useState(new Date());

  // Search and Pagination State
  const [searchTicketId, setSearchTicketId] = useState('');
  const [wfOffset, setWfOffset] = useState(0);
  const [intOffset, setIntOffset] = useState(0);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = {};
      if (searchTicketId.length === 36) { // Valid UUID length
        params.ticket_id = searchTicketId;
      }

      const [statusRes, historyRes, workflowRes, interactionRes] = await Promise.all([
        api.get('system/status/'),
        api.get('system/history/'),
        api.get('system/workflows/', { params: { ...params, offset: wfOffset, limit: PAGE_SIZE } }),
        api.get('system/interactions/', { params: { ...params, offset: intOffset, limit: PAGE_SIZE } })
      ]);

      if (statusRes.data) setStatus(statusRes.data);
      
      if (historyRes.data) {
        const grouped: InfraHistory = { DATABASE: [], REDIS: [], OLLAMA: [] };
        historyRes.data.forEach((entry: any) => {
          if (grouped[entry.service_name as keyof InfraHistory]) {
            grouped[entry.service_name as keyof InfraHistory].push(entry.latency_ms);
          }
        });
        setHistory(grouped);
      }

      if (workflowRes.data) setWorkflows(workflowRes.data);
      if (interactionRes.data) setInteractions(interactionRes.data);
    } catch (err) {
      console.error('Failed to monitor sys stats', err);
    } finally {
      setTimeout(() => {
        setLoading(false);
        setLastRefreshed(new Date());
      }, 400);
    }
  }, [searchTicketId, wfOffset, intOffset]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchTicketId(e.target.value);
    setWfOffset(0);
    setIntOffset(0);
  };

  return (
    <div className={styles.container}>
      <header className={styles.header}>
        <motion.div
           initial={{ opacity: 0, x: -20 }}
           animate={{ opacity: 1, x: 0 }}
        >
          <h1>Nexus Control</h1>
          <p>Real-time infrastructure health and autonomous agent auditing</p>
        </motion.div>
        
        <div style={{ display: 'flex', alignItems: 'center', gap: '2rem' }}>
          <div className={styles.searchInputWrapper}>
             <Search size={16} className={styles.searchIcon} />
             <input 
                type="text" 
                className={styles.searchInput} 
                placeholder="Search Ticket ID (UUID)..." 
                value={searchTicketId}
                onChange={handleSearch}
             />
          </div>

          <div style={{ textAlign: 'right' }}>
            <button 
              className={styles.refreshBtn}
              onClick={fetchData}
              disabled={loading}
            >
              <RefreshCcw size={16} className={loading ? 'spinning' : ''} />
              Diagnostics
            </button>
            <div style={{ display: 'flex', alignItems: 'center', gap: '0.4rem', color: 'var(--text3)', fontSize: '0.75rem', marginTop: '1rem', fontWeight: 600 }}>
              <Clock size={12} />
              Sync: {lastRefreshed.toLocaleTimeString()}
            </div>
          </div>
        </div>
      </header>

      <section className={styles.grid}>
        <StatusCard 
          title="Database Cluster" 
          node={status?.database} 
          history={history.DATABASE}
          icon={Database} 
          color="#3b82f6" 
          loading={loading}
        />
        <StatusCard 
          title="Workflow Queue" 
          node={status?.redis} 
          history={history.REDIS}
          icon={Zap} 
          color="#ec4899" 
          loading={loading}
        />
        <StatusCard 
          title="Inference Node" 
          node={status?.ollama} 
          history={history.OLLAMA}
          icon={Brain} 
          color="#8b5cf6" 
          loading={loading}
        />
      </section>

      <div className={styles.sectionGrid}>
        {/* Aggregated Workflows */}
        <section className={styles.section}>
          <div className={styles.sectionHeader}>
            <div>
              <div className={styles.sectionTitle}>
                <Layout size={22} color="var(--accent)" />
                Service Logic
              </div>
              <div className={styles.sectionSub}>Ticket Resolution Pipelines</div>
            </div>
            
            <div className={styles.pagination}>
               <button 
                  className={styles.pageBtn} 
                  disabled={loading || wfOffset === 0}
                  onClick={() => setWfOffset(Math.max(0, wfOffset - PAGE_SIZE))}
               >
                 <ChevronLeft size={14} /> Prev
               </button>
               <button 
                  className={styles.pageBtn}
                  disabled={loading || workflows.length < PAGE_SIZE}
                  onClick={() => setWfOffset(wfOffset + PAGE_SIZE)}
               >
                 Next <ChevronRight size={14} />
               </button>
            </div>
          </div>

          <div className={styles.list}>
            <AnimatePresence mode="popLayout">
              {workflows.map((wf, idx) => (
                <motion.div 
                  key={wf.id} 
                  className={styles.item}
                  initial={{ opacity: 0, y: 10 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: idx * 0.05 }}
                >
                  <div className={styles.itemMeta}>
                    <div className={styles.typeBadge}>
                      <Workflow size={14} color="var(--accent)" />
                      {wf.workflow_type}
                      <span className={styles.idTag}>#{wf.entity_id.slice(0,6)}</span>
                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '1rem' }}>
                      <div className={styles.statusBadge}>{wf.current_stage}</div>
                      <div style={{ fontSize: '0.75rem', fontWeight: 900, color: 'var(--text3)' }}>
                        {wf.total_duration_ms.toFixed(0)}<span style={{ fontSize: '0.6rem', opacity: 0.6, marginLeft: '2px' }}>ms</span>
                      </div>
                    </div>
                  </div>

                  <div className={styles.track}>
                    {wf.steps.map((step, sIdx) => (
                      <React.Fragment key={sIdx}>
                        <div className={styles.step}>
                          <div className={`${styles.node} ${step.status}`} />
                          <div className={styles.nodeLabel}>{step.name}</div>
                        </div>
                        {sIdx < wf.steps.length - 1 && <div className={styles.connector} />}
                      </React.Fragment>
                    ))}
                  </div>
                </motion.div>
              ))}
              {workflows.length === 0 && !loading && (
                <div style={{ textAlign: 'center', padding: '4rem', color: 'var(--text3)' }}>
                  No historical workflows found matching query.
                </div>
              )}
            </AnimatePresence>
          </div>
        </section>

        {/* Granular Interactions */}
        <section className={styles.section} style={{ background: 'rgba(255, 255, 255, 0.8)' }}>
          <div className={styles.sectionHeader}>
            <div>
              <div className={styles.sectionTitle}>
                <Activity size={22} color="#ec4899" />
                Agent Audit
              </div>
              <div className={styles.sectionSub}>Live Autonomous Reasoning</div>
            </div>

            <div className={styles.pagination}>
               <button 
                  className={styles.pageBtn} 
                  disabled={loading || intOffset === 0}
                  onClick={() => setIntOffset(Math.max(0, intOffset - PAGE_SIZE))}
               >
                 <ChevronLeft size={14} /> Prev
               </button>
               <button 
                  className={styles.pageBtn}
                  disabled={loading || interactions.length < PAGE_SIZE}
                  onClick={() => setIntOffset(intOffset + PAGE_SIZE)}
               >
                 Next <ChevronRight size={14} />
               </button>
            </div>
          </div>

          <div className={styles.list}>
             {interactions.map((interaction, idx) => {
               const steps = interaction.output_data?.processed_steps || [];
               const errors = interaction.output_data?.errors || [];
               const duration = typeof interaction.duration_ms === 'number' ? interaction.duration_ms : interaction.duration_ms?.total || 0;

               return (
                 <motion.div 
                   key={interaction.id} 
                   className={styles.item}
                   initial={{ opacity: 0, scale: 0.95 }}
                   animate={{ opacity: 1, scale: 1 }}
                   transition={{ delay: idx * 0.03 }}
                 >
                   <div className={styles.itemMeta}>
                     <div className={styles.agentHeader}>
                        <div className={styles.agentIcon}>{getAgentIcon(interaction.agent_name)}</div>
                        <div className={styles.agentName}>{interaction.agent_name.replace('_node', '')}</div>
                        <div style={{ marginLeft: '1rem', fontSize: '0.75rem', fontWeight: 900, color: 'var(--text3)' }}>
                          {duration.toFixed(0)}<span style={{ fontSize: '0.6rem', opacity: 0.6, marginLeft: '2px' }}>ms</span>
                        </div>
                     </div>
                     <div style={{ textAlign: 'right' }}>
                        <div style={{ fontSize: '0.7rem', fontWeight: 700, color: 'var(--text3)' }}>
                          {new Date(interaction.created_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}
                        </div>
                        {interaction.ticket_id && <div style={{ fontSize: '0.65rem', color: 'var(--accent)', fontWeight: 600 }}>TICKET #{interaction.ticket_id.slice(0,6)}</div>}
                     </div>
                   </div>

                   <div className={styles.track}>
                      {steps.map((s: any, sIdx: number) => (
                        <React.Fragment key={sIdx}>
                          <div className={styles.step}>
                            <div className={`${styles.node} ${s.status}`} />
                            <div className={styles.nodeLabel}>{s.name}</div>
                          </div>
                          {sIdx < steps.length - 1 && <div className={styles.connector} />}
                        </React.Fragment>
                      ))}
                      {steps.length === 0 && <div style={{ fontSize: '0.7rem', color: 'var(--text3)', fontStyle: 'italic' }}>Node initiating...</div>}
                   </div>

                   {(errors.length > 0 || interaction.status === 'error') && (
                     <div className={styles.errorAura}>
                        <div className={styles.errorTitle}>
                          <AlertCircle size={14} />
                          Trace failure pinpointed
                        </div>
                        <div className={styles.errorText}>
                          {errors[0] || 'Unresponsive agent node. Reviewing local inference logs.'}
                        </div>
                     </div>
                   )}
                 </motion.div>
               );
             })}
             {interactions.length === 0 && !loading && (
                <div style={{ textAlign: 'center', padding: '4rem', color: 'var(--text3)' }}>
                  No granular interactions found matching query.
                </div>
              )}
          </div>
        </section>
      </div>
    </div>
  );
};

export default InfraMonitor;