File size: 34,573 Bytes
3f5fadf
fef95f5
 
3f5fadf
 
 
be213f1
3f5fadf
be213f1
2aa7110
b20e8fd
7ebbb94
2aa7110
 
 
11cd487
3f5fadf
fef95f5
 
 
 
9d7ff51
fef95f5
9d7ff51
 
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7450c87
fef95f5
 
 
a82ff13
fef95f5
 
 
 
 
 
 
 
 
 
 
a82ff13
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
a82ff13
fef95f5
a82ff13
fef95f5
 
a82ff13
fef95f5
 
b20e8fd
fef95f5
a82ff13
fef95f5
 
 
b20e8fd
a82ff13
fef95f5
b20e8fd
fef95f5
b20e8fd
a82ff13
 
fef95f5
b20e8fd
fef95f5
 
 
a82ff13
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
 
 
 
 
a82ff13
7c722fd
a82ff13
 
 
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9d7ff51
 
 
fef95f5
 
 
 
 
 
 
 
9d7ff51
 
 
 
fef95f5
9d7ff51
4335b20
fef95f5
 
 
 
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
b20e8fd
 
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a82ff13
fef95f5
 
 
 
be213f1
9d7ff51
fef95f5
9d7ff51
3f5fadf
fef95f5
 
2aa7110
fef95f5
 
 
 
 
 
 
 
 
a82ff13
b20e8fd
 
 
 
11cd487
b20e8fd
 
3f5fadf
fef95f5
b20e8fd
 
 
fef95f5
b20e8fd
 
 
 
fef95f5
 
b20e8fd
 
7c722fd
 
b20e8fd
fef95f5
 
 
7c722fd
b20e8fd
fef95f5
 
 
b20e8fd
fef95f5
b20e8fd
fef95f5
b20e8fd
fef95f5
b20e8fd
 
 
 
7c722fd
fef95f5
7c722fd
fef95f5
7c722fd
b20e8fd
 
7c722fd
fef95f5
b20e8fd
 
 
 
 
7c722fd
fef95f5
 
 
 
7c722fd
fef95f5
b20e8fd
 
 
 
a82ff13
fef95f5
 
 
 
b20e8fd
7450c87
b20e8fd
fef95f5
b20e8fd
fef95f5
b20e8fd
fef95f5
7450c87
fef95f5
b20e8fd
 
 
fef95f5
b20e8fd
 
 
fef95f5
b20e8fd
 
 
fef95f5
b20e8fd
 
 
 
a82ff13
b20e8fd
fef95f5
 
 
 
a82ff13
fef95f5
b20e8fd
 
 
 
 
 
fef95f5
b20e8fd
 
fef95f5
b20e8fd
 
 
 
 
 
fef95f5
b20e8fd
 
fef95f5
b20e8fd
 
fef95f5
 
b20e8fd
fef95f5
b20e8fd
 
 
 
 
 
 
 
 
fef95f5
 
 
b20e8fd
fef95f5
 
b20e8fd
a82ff13
fef95f5
b20e8fd
fef95f5
b20e8fd
 
 
 
 
 
fef95f5
b20e8fd
 
 
 
 
 
 
fef95f5
b20e8fd
 
 
fef95f5
b20e8fd
fef95f5
 
 
 
 
 
 
 
 
b20e8fd
 
fef95f5
 
 
 
 
 
11cd487
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
 
fef95f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b20e8fd
 
fef95f5
7342596
9d7ff51
b20e8fd
9d7ff51
7ebbb94
b20e8fd
fef95f5
 
 
 
 
9d7ff51
fef95f5
7ebbb94
 
 
 
fef95f5
 
b20e8fd
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
"""
๐Ÿš€ ARF ULTIMATE INVESTOR DEMO v3.5.0 - FULLY WORKING VERSION
All buttons working, all visualizations rendering, no errors
"""

import datetime
import json
import logging
import uuid
import random
from typing import Dict, Any, List
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from plotly.subplots import make_subplots

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# ===========================================
# INCIDENT DATA STORAGE
# ===========================================

INCIDENT_SCENARIOS = {
    "Cache Miss Storm": {
        "metrics": {
            "Cache Hit Rate": "18.5% (Critical)",
            "Database Load": "92% (Overloaded)",
            "Response Time": "1850ms (Slow)",
            "Affected Users": "45,000"
        },
        "impact": {
            "Revenue Loss": "$8,500/hour",
            "Page Load Time": "+300%",
            "Users Impacted": "45,000"
        },
        "oss_analysis": {
            "status": "โœ… Analysis Complete",
            "recommendations": [
                "Increase Redis cache memory allocation",
                "Implement cache warming strategy",
                "Optimize key patterns (TTL adjustments)",
                "Add circuit breaker for database fallback"
            ],
            "estimated_time": "60+ minutes",
            "engineers_needed": "2-3 SREs",
            "manual_effort": "High"
        },
        "enterprise_results": {
            "actions_completed": [
                "โœ… Auto-scaled Redis: 4GB โ†’ 8GB",
                "โœ… Deployed cache warming service",
                "โœ… Optimized 12 key patterns",
                "โœ… Implemented circuit breaker"
            ],
            "metrics_improvement": {
                "Cache Hit Rate": "18.5% โ†’ 72%",
                "Response Time": "1850ms โ†’ 450ms",
                "Database Load": "92% โ†’ 45%"
            },
            "business_impact": {
                "Recovery Time": "60 min โ†’ 12 min",
                "Cost Saved": "$7,200",
                "Users Impacted": "45,000 โ†’ 0"
            }
        }
    },
    "Database Connection Pool Exhaustion": {
        "metrics": {
            "Active Connections": "98/100 (Critical)",
            "API Latency": "2450ms",
            "Error Rate": "15.2%",
            "Queue Depth": "1250"
        },
        "impact": {
            "Revenue Loss": "$4,200/hour",
            "Affected Services": "API Gateway, User Service",
            "SLA Violation": "Yes"
        },
        "oss_analysis": {
            "status": "โœ… Analysis Complete",
            "recommendations": [
                "Increase connection pool from 100 to 200",
                "Add connection timeout (30s)",
                "Implement leak detection",
                "Add connection health checks"
            ],
            "estimated_time": "45+ minutes",
            "engineers_needed": "1-2 DBAs",
            "manual_effort": "Medium-High"
        }
    },
    "Memory Leak in Production": {
        "metrics": {
            "Memory Usage": "96% (Critical)",
            "GC Pause Time": "4500ms",
            "Error Rate": "28.5%",
            "Restart Frequency": "12/hour"
        },
        "impact": {
            "Revenue Loss": "$5,500/hour",
            "Session Loss": "8,500 users",
            "Customer Impact": "High"
        }
    }
}

# ===========================================
# VISUALIZATION ENGINE
# ===========================================

class VisualizationEngine:
    """Working visualization engine with no errors"""
    
    @staticmethod
    def create_timeline_visualization():
        """Create interactive incident timeline"""
        try:
            # Create sample timeline data
            now = datetime.datetime.now()
            events = [
                {"time": now - datetime.timedelta(minutes=25), "event": "๐Ÿ“‰ Cache Hit Rate drops to 18.5%", "type": "problem"},
                {"time": now - datetime.timedelta(minutes=22), "event": "โš ๏ธ Alert: Database load hits 92%", "type": "alert"},
                {"time": now - datetime.timedelta(minutes=20), "event": "๐Ÿค– ARF detects pattern", "type": "detection"},
                {"time": now - datetime.timedelta(minutes=18), "event": "๐Ÿง  Analysis: Cache Miss Storm identified", "type": "analysis"},
                {"time": now - datetime.timedelta(minutes=15), "event": "โšก Enterprise healing executed", "type": "action"},
                {"time": now - datetime.timedelta(minutes=12), "event": "โœ… Cache Hit Rate recovers to 72%", "type": "recovery"},
                {"time": now - datetime.timedelta(minutes=10), "event": "๐Ÿ“Š System stabilized", "type": "stable"}
            ]
            
            df = pd.DataFrame(events)
            df['time_str'] = df['time'].dt.strftime('%H:%M:%S')
            
            # Color mapping
            color_map = {
                "problem": "red",
                "alert": "orange", 
                "detection": "blue",
                "analysis": "purple",
                "action": "green",
                "recovery": "lightgreen",
                "stable": "darkgreen"
            }
            
            fig = go.Figure()
            
            for event_type in df['type'].unique():
                type_df = df[df['type'] == event_type]
                fig.add_trace(go.Scatter(
                    x=type_df['time'],
                    y=[event_type] * len(type_df),
                    mode='markers+text',
                    name=event_type.capitalize(),
                    marker=dict(
                        size=15,
                        color=color_map.get(event_type, 'gray'),
                        symbol='circle' if event_type in ['problem', 'alert'] else 'diamond',
                        line=dict(width=2, color='white')
                    ),
                    text=type_df['event'],
                    textposition="top center",
                    hoverinfo='text'
                ))
            
            fig.update_layout(
                title="<b>Incident Timeline - Cache Miss Storm Resolution</b>",
                xaxis_title="Time โ†’",
                yaxis_title="Event Type",
                height=500,
                showlegend=True,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)',
                hovermode='closest',
                xaxis=dict(
                    tickformat='%H:%M',
                    gridcolor='rgba(200,200,200,0.2)'
                ),
                yaxis=dict(
                    gridcolor='rgba(200,200,200,0.1)'
                )
            )
            
            return fig
        except Exception as e:
            logger.error(f"Error creating timeline: {e}")
            return VisualizationEngine._create_error_figure("Timeline")
    
    @staticmethod
    def create_business_dashboard():
        """Create business health dashboard"""
        try:
            fig = make_subplots(
                rows=2, cols=2,
                subplot_titles=('Annual Cost Impact', 'Team Time Reclaimed',
                              'MTTR Comparison', 'ROI Analysis'),
                vertical_spacing=0.15,
                horizontal_spacing=0.15
            )
            
            # 1. Cost Impact
            categories = ['Without ARF', 'With ARF Enterprise', 'Net Savings']
            values = [2960000, 1000000, 1960000]
            
            fig.add_trace(
                go.Bar(
                    x=categories,
                    y=values,
                    marker_color=['#FF6B6B', '#4ECDC4', '#45B7D1'],
                    text=[f'${v/1000000:.1f}M' for v in values],
                    textposition='auto',
                    name='Cost Impact'
                ),
                row=1, col=1
            )
            
            # 2. Time Allocation
            labels = ['Firefighting', 'Innovation', 'Maintenance']
            before = [60, 20, 20]
            after = [10, 60, 30]
            
            fig.add_trace(
                go.Bar(
                    x=labels,
                    y=before,
                    name='Before ARF',
                    marker_color='#FF6B6B'
                ),
                row=1, col=2
            )
            
            fig.add_trace(
                go.Bar(
                    x=labels,
                    y=after,
                    name='After ARF Enterprise',
                    marker_color='#4ECDC4'
                ),
                row=1, col=2
            )
            
            # 3. MTTR Comparison
            mttr_categories = ['Traditional', 'ARF OSS', 'ARF Enterprise']
            mttr_values = [45, 25, 8]
            
            fig.add_trace(
                go.Bar(
                    x=mttr_categories,
                    y=mttr_values,
                    marker_color=['#FF6B6B', '#FFE66D', '#4ECDC4'],
                    text=[f'{v} min' for v in mttr_values],
                    textposition='auto',
                    name='MTTR'
                ),
                row=2, col=1
            )
            
            # 4. ROI Gauge
            fig.add_trace(
                go.Indicator(
                    mode="gauge+number+delta",
                    value=5.2,
                    title={'text': "ROI Multiplier"},
                    delta={'reference': 1.0, 'increasing': {'color': "green"}},
                    gauge={
                        'axis': {'range': [0, 10], 'tickwidth': 1},
                        'bar': {'color': "#4ECDC4"},
                        'steps': [
                            {'range': [0, 2], 'color': "lightgray"},
                            {'range': [2, 4], 'color': "gray"},
                            {'range': [4, 6], 'color': "lightgreen"},
                            {'range': [6, 10], 'color': "green"}
                        ],
                        'threshold': {
                            'line': {'color': "red", 'width': 4},
                            'thickness': 0.75,
                            'value': 5.2
                        }
                    }
                ),
                row=2, col=2
            )
            
            fig.update_layout(
                height=700,
                showlegend=True,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)',
                title_text="<b>Executive Business Health Dashboard</b>",
                barmode='group'
            )
            
            # Update axes
            fig.update_xaxes(title_text="Cost Categories", row=1, col=1)
            fig.update_yaxes(title_text="Annual Cost ($)", row=1, col=1)
            
            fig.update_xaxes(title_text="Activity Type", row=1, col=2)
            fig.update_yaxes(title_text="Percentage (%)", row=1, col=2)
            
            fig.update_xaxes(title_text="Solution Type", row=2, col=1)
            fig.update_yaxes(title_text="Minutes to Resolve", row=2, col=1)
            
            return fig
        except Exception as e:
            logger.error(f"Error creating dashboard: {e}")
            return VisualizationEngine._create_error_figure("Dashboard")
    
    @staticmethod
    def create_metrics_stream():
        """Create metrics stream visualization"""
        try:
            # Generate time series data
            times = pd.date_range(end=datetime.datetime.now(), periods=50, freq='1min')
            
            fig = go.Figure()
            
            # Cache Hit Rate
            fig.add_trace(go.Scatter(
                x=times,
                y=[18.5 + i * 1.2 for i in range(50)],  # Recovery trend
                mode='lines',
                name='Cache Hit Rate',
                line=dict(color='blue', width=2),
                yaxis='y1'
            ))
            
            # Database Load
            fig.add_trace(go.Scatter(
                x=times,
                y=[92 - i * 0.94 for i in range(50)],  # Decreasing trend
                mode='lines',
                name='Database Load',
                line=dict(color='red', width=2),
                yaxis='y2'
            ))
            
            fig.update_layout(
                title="<b>Real-time Metrics Recovery</b>",
                xaxis_title="Time",
                height=500,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)',
                yaxis=dict(
                    title="Cache Hit Rate (%)",
                    side='left',
                    range=[0, 100]
                ),
                yaxis2=dict(
                    title="Database Load (%)",
                    side='right',
                    overlaying='y',
                    range=[0, 100]
                ),
                legend=dict(
                    yanchor="top",
                    y=0.99,
                    xanchor="left",
                    x=0.01
                )
            )
            
            return fig
        except Exception as e:
            logger.error(f"Error creating stream: {e}")
            return VisualizationEngine._create_error_figure("Metrics Stream")
    
    @staticmethod
    def create_performance_radar():
        """Create performance radar chart"""
        try:
            categories = ['Reliability', 'Speed', 'Cost Savings', 'Auto-Heal Rate', 'ROI']
            values = [95, 88, 92, 82, 85]
            
            fig = go.Figure(data=go.Scatterpolar(
                r=values + [values[0]],
                theta=categories + [categories[0]],
                fill='toself',
                fillcolor='rgba(52, 152, 219, 0.3)',
                line=dict(color='rgba(52, 152, 219, 0.8)', width=2),
                name="ARF Enterprise"
            ))
            
            fig.update_layout(
                polar=dict(
                    radialaxis=dict(
                        visible=True,
                        range=[0, 100],
                        gridcolor='rgba(200, 200, 200, 0.3)'
                    )),
                showlegend=True,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)',
                height=500,
                title="<b>Performance Radar - ARF Enterprise</b>"
            )
            
            return fig
        except Exception as e:
            logger.error(f"Error creating radar: {e}")
            return VisualizationEngine._create_error_figure("Radar Chart")
    
    @staticmethod
    def create_execution_history():
        """Create execution history chart"""
        try:
            executions = [
                {"time": "22:14", "scenario": "Cache Miss Storm", "savings": 7200},
                {"time": "21:58", "scenario": "Memory Leak", "savings": 5200},
                {"time": "21:45", "scenario": "API Rate Limit", "savings": 2800},
                {"time": "21:30", "scenario": "DB Pool Exhaustion", "savings": 3800},
                {"time": "21:15", "scenario": "Cache Miss Storm", "savings": 7200},
                {"time": "21:00", "scenario": "Cascading Failure", "savings": 12500}
            ]
            
            df = pd.DataFrame(executions)
            
            fig = go.Figure(data=[
                go.Bar(
                    x=df['scenario'],
                    y=df['savings'],
                    marker_color='#4ECDC4',
                    text=[f'${s:,.0f}' for s in df['savings']],
                    textposition='outside',
                    name='Cost Saved'
                )
            ])
            
            fig.update_layout(
                title="<b>Execution History - Cost Savings</b>",
                xaxis_title="Incident Scenario",
                yaxis_title="Cost Saved ($)",
                height=500,
                paper_bgcolor='rgba(0,0,0,0)',
                plot_bgcolor='rgba(0,0,0,0)',
                showlegend=False
            )
            
            return fig
        except Exception as e:
            logger.error(f"Error creating history chart: {e}")
            return VisualizationEngine._create_error_figure("History Chart")
    
    @staticmethod
    def _create_error_figure(chart_type: str):
        """Create error figure with message"""
        fig = go.Figure()
        fig.update_layout(
            paper_bgcolor='rgba(0,0,0,0)',
            plot_bgcolor='rgba(0,0,0,0)',
            height=400,
            annotations=[dict(
                text=f"{chart_type} visualization<br>will appear here",
                xref="paper", yref="paper",
                x=0.5, y=0.5,
                showarrow=False,
                font=dict(size=16, color="gray")
            )]
        )
        return fig

# ===========================================
# MAIN APPLICATION
# ===========================================

def run_oss_analysis(scenario_name: str):
    """Run OSS analysis - NOW WORKING"""
    try:
        scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
        analysis = scenario.get("oss_analysis", {})
        
        if not analysis:
            analysis = {
                "status": "โœ… Analysis Complete",
                "recommendations": [
                    "Increase resource allocation",
                    "Implement monitoring",
                    "Add circuit breakers",
                    "Optimize configuration"
                ],
                "estimated_time": "45-60 minutes",
                "engineers_needed": "2-3",
                "manual_effort": "Required"
            }
        
        return analysis
    except Exception as e:
        logger.error(f"OSS analysis error: {e}")
        return {
            "status": "โŒ Analysis Failed",
            "error": "Please try again",
            "recommendations": ["Check system configuration"]
        }

def execute_enterprise_healing(scenario_name: str, approval_required: bool):
    """Execute enterprise healing - NOW WORKING"""
    try:
        scenario = INCIDENT_SCENARIOS.get(scenario_name, {})
        results = scenario.get("enterprise_results", {})
        
        if not results:
            results = {
                "status": "โœ… Auto-Executed" if not approval_required else "โœ… Approved and Executed",
                "actions_completed": [
                    "โœ… Auto-scaled resources",
                    "โœ… Implemented optimization",
                    "โœ… Deployed monitoring",
                    "โœ… Validated recovery"
                ],
                "cost_saved": f"${random.randint(2000, 8000):,}",
                "time_savings": f"{random.randint(30, 60)} min โ†’ {random.randint(5, 15)} min"
            }
        
        # Add approval info
        if approval_required:
            approval_html = f"""
            <div style='padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #007bff; margin: 10px 0;'>
            <h4 style='margin: 0 0 10px 0;'>๐Ÿ›ก๏ธ Approval Required</h4>
            <p><b>Action:</b> Scale cache for {scenario_name}</p>
            <p><b>Risk:</b> Low (auto-rollback available)</p>
            <p><b>Status:</b> โœ… <span style='color: green;'>Approved & Executed</span></p>
            </div>
            """
        else:
            approval_html = f"""
            <div style='padding: 15px; background: #e8f5e8; border-radius: 8px; border-left: 4px solid #28a745; margin: 10px 0;'>
            <h4 style='margin: 0 0 10px 0;'>โšก Auto-Executed</h4>
            <p><b>Action:</b> Autonomous healing for {scenario_name}</p>
            <p><b>Mode:</b> Fully autonomous (guardrails active)</p>
            <p><b>Status:</b> โœ… <span style='color: green;'>Successfully completed</span></p>
            </div>
            """
        
        return approval_html, {"approval_required": approval_required, "compliance_mode": "strict"}, results
    except Exception as e:
        logger.error(f"Enterprise execution error: {e}")
        error_html = f"<div style='color: red; padding: 10px;'>โŒ Execution error: {str(e)}</div>"
        return error_html, {"error": True}, {"status": "Failed"}

def update_visualization(scenario_name: str, viz_type: str):
    """Update visualization based on selection"""
    try:
        viz_engine = VisualizationEngine()
        
        if viz_type == "Interactive Timeline":
            return viz_engine.create_timeline_visualization()
        elif viz_type == "Metrics Stream":
            return viz_engine.create_metrics_stream()
        elif viz_type == "Performance Radar":
            return viz_engine.create_performance_radar()
        else:
            return viz_engine.create_timeline_visualization()
    except Exception as e:
        logger.error(f"Visualization error: {e}")
        return VisualizationEngine._create_error_figure("Visualization")

def calculate_roi(monthly_incidents: int, avg_impact: int, team_size: int):
    """Calculate ROI - NOW WORKING"""
    try:
        annual_impact = monthly_incidents * 12 * avg_impact
        team_cost = team_size * 150000  # $150k per engineer
        savings = annual_impact * 0.82  # 82% savings with ARF
        
        if team_cost > 0:
            roi_multiplier = savings / team_cost
        else:
            roi_multiplier = 0
        
        # Determine recommendation
        if roi_multiplier >= 5.0:
            recommendation = "โœ… Excellent fit for ARF Enterprise"
            icon = "๐Ÿš€"
        elif roi_multiplier >= 2.0:
            recommendation = "โœ… Good ROI with ARF Enterprise"
            icon = "โœ…"
        elif roi_multiplier >= 1.0:
            recommendation = "โš ๏ธ Consider ARF OSS edition first"
            icon = "โ„น๏ธ"
        else:
            recommendation = "โš ๏ธ Start with ARF OSS (free)"
            icon = "๐Ÿ†“"
        
        return {
            "analysis": {
                "your_annual_impact": f"${annual_impact:,.0f}",
                "your_team_cost": f"${team_cost:,.0f}",
                "potential_savings": f"${savings:,.0f}",
                "your_roi_multiplier": f"{roi_multiplier:.1f}ร—",
                "vs_industry_average": "5.2ร— average ROI",
                "recommendation": f"{icon} {recommendation}",
                "payback_period": f"{(team_cost / (savings / 12)):.1f} months" if savings > 0 else "N/A"
            }
        }
    except Exception as e:
        logger.error(f"ROI calculation error: {e}")
        return {"error": f"Calculation error: {str(e)}"}

# ===========================================
# GRADIO INTERFACE
# ===========================================

def create_interface():
    """Create the Gradio interface"""
    
    with gr.Blocks(
        title="๐Ÿš€ ARF Investor Demo v3.5.0",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container { max-width: 1200px; margin: auto; }
        h1, h2, h3 { color: #1a365d !important; }
        .primary-button { background: linear-gradient(90deg, #667eea 0%, #764ba2 100%) !important; }
        """
    ) as demo:
        
        # ============ HEADER ============
        gr.Markdown("""
        # ๐Ÿš€ Agentic Reliability Framework - Investor Demo v3.5.0
        ## From Cost Center to Profit Engine: 5.2ร— ROI with Autonomous Reliability
        
        **Experience the transformation:** OSS (Advisory) โ†” Enterprise (Autonomous)
        """)
        
        # ============ MAIN TABS ============
        with gr.Tabs():
            
            # TAB 1: LIVE INCIDENT DEMO
            with gr.TabItem("๐Ÿ”ฅ Live Incident Demo", id="live-demo"):
                with gr.Row():
                    # Left Panel
                    with gr.Column(scale=1):
                        gr.Markdown("### ๐ŸŽฌ Incident Scenario")
                        scenario_dropdown = gr.Dropdown(
                            choices=list(INCIDENT_SCENARIOS.keys()),
                            value="Cache Miss Storm",
                            label="Select critical incident:"
                        )
                        
                        gr.Markdown("### ๐Ÿ“Š Current Crisis Metrics")
                        metrics_display = gr.JSON(
                            value=INCIDENT_SCENARIOS["Cache Miss Storm"]["metrics"]
                        )
                        
                        gr.Markdown("### ๐Ÿ’ฐ Business Impact")
                        impact_display = gr.JSON(
                            value=INCIDENT_SCENARIOS["Cache Miss Storm"]["impact"]
                        )
                    
                    # Right Panel
                    with gr.Column(scale=2):
                        # Visualization
                        gr.Markdown("### ๐Ÿ“ˆ Incident Timeline Visualization")
                        viz_radio = gr.Radio(
                            choices=["Interactive Timeline", "Metrics Stream", "Performance Radar"],
                            value="Interactive Timeline",
                            label="Choose visualization:"
                        )
                        
                        timeline_output = gr.Plot()
                        
                        # Action Buttons
                        with gr.Row():
                            oss_btn = gr.Button("๐Ÿ†“ Run OSS Analysis", variant="secondary")
                            enterprise_btn = gr.Button("๐Ÿš€ Execute Enterprise Healing", variant="primary")
                        
                        # Approval Toggle
                        approval_toggle = gr.Checkbox(
                            label="๐Ÿ” Require Manual Approval",
                            value=True,
                            info="Toggle to show approval workflow vs auto-execution"
                        )
                        
                        # Approval Display
                        approval_display = gr.HTML(
                            value="<div style='padding: 10px; background: #f8f9fa; border-radius: 5px;'>Approval status will appear here</div>"
                        )
                        
                        # Configuration
                        config_display = gr.JSON(
                            label="โš™๏ธ Enterprise Configuration",
                            value={"approval_required": True, "compliance_mode": "strict"}
                        )
                        
                        # Results
                        results_display = gr.JSON(
                            label="๐ŸŽฏ Execution Results",
                            value={"status": "Ready for execution..."}
                        )
            
            # TAB 2: BUSINESS IMPACT & ROI
            with gr.TabItem("๐Ÿ’ฐ Business Impact & ROI", id="business-roi"):
                with gr.Column():
                    # Business Dashboard
                    gr.Markdown("### ๐Ÿ“Š Business Health Dashboard")
                    dashboard_output = gr.Plot()
                    
                    # ROI Calculator
                    gr.Markdown("### ๐Ÿงฎ Interactive ROI Calculator")
                    with gr.Row():
                        with gr.Column(scale=1):
                            monthly_slider = gr.Slider(
                                1, 100, value=15, step=1,
                                label="Monthly incidents"
                            )
                            impact_slider = gr.Slider(
                                1000, 50000, value=8500, step=500,
                                label="Avg incident impact ($)"
                            )
                            team_slider = gr.Slider(
                                1, 20, value=5, step=1,
                                label="Reliability team size"
                            )
                            calculate_btn = gr.Button("Calculate My ROI", variant="primary")
                        
                        with gr.Column(scale=2):
                            roi_output = gr.JSON(
                                label="Your ROI Analysis",
                                value={"analysis": "Adjust sliders and click 'Calculate My ROI'"}
                            )
                    
                    # Capability Comparison
                    gr.Markdown("### ๐Ÿ“‹ Capability Comparison")
                    with gr.Row():
                        with gr.Column():
                            gr.Markdown("""
                            **OSS Edition (Free)**
                            - Advisory recommendations only
                            - Manual implementation required
                            - No auto-healing
                            - Community support
                            - No ROI measurement
                            """)
                        with gr.Column():
                            gr.Markdown("""
                            **Enterprise Edition**
                            - Autonomous execution
                            - 81.7% auto-heal rate
                            - Full audit trails & compliance
                            - 24/7 enterprise support
                            - 5.2ร— average ROI
                            - 2-3 month payback
                            """)
            
            # TAB 3: AUDIT TRAIL
            with gr.TabItem("๐Ÿ“œ Audit Trail", id="audit-trail"):
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### ๐Ÿ“‹ Recent Executions")
                        with gr.Row():
                            refresh_btn = gr.Button("๐Ÿ”„ Refresh", size="sm")
                            clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear All", variant="stop", size="sm")
                        
                        audit_table = gr.Dataframe(
                            headers=["Time", "Scenario", "Actions", "Status", "Savings"],
                            value=[
                                ["22:14", "Cache Miss Storm", "4", "โœ… Executed", "$7,200"],
                                ["21:58", "Memory Leak", "3", "โœ… Executed", "$5,200"],
                                ["21:45", "API Rate Limit", "4", "โœ… Executed", "$2,800"],
                                ["21:30", "DB Connection Pool", "4", "โœ… Executed", "$3,800"]
                            ],
                            interactive=False,
                            wrap=True
                        )
                    
                    with gr.Column(scale=2):
                        gr.Markdown("### ๐Ÿ“ˆ Execution History")
                        history_output = gr.Plot()
        
        # ============ FOOTER ============
        gr.Markdown("---")
        with gr.Row():
            with gr.Column(scale=2):
                gr.Markdown("""
                **๐Ÿ“ž Contact & Demo**  
                ๐Ÿ“ง enterprise@arf.dev  
                ๐ŸŒ [https://arf.dev](https://arf.dev)  
                ๐Ÿ“š [Documentation](https://docs.arf.dev)  
                ๐Ÿ’ป [GitHub](https://github.com/petterjuan/agentic-reliability-framework)
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
                **๐ŸŽฏ Schedule a Demo**  
                [https://arf.dev/demo](https://arf.dev/demo)
                """)
        
        # ============ EVENT HANDLERS ============
        
        # Scenario change updates metrics and visualization
        scenario_dropdown.change(
            lambda name: (
                INCIDENT_SCENARIOS.get(name, {}).get("metrics", {}),
                INCIDENT_SCENARIOS.get(name, {}).get("impact", {}),
                update_visualization(name, "Interactive Timeline")
            ),
            inputs=[scenario_dropdown],
            outputs=[metrics_display, impact_display, timeline_output]
        )
        
        # Visualization type change
        viz_radio.change(
            lambda scenario, viz: update_visualization(scenario, viz),
            inputs=[scenario_dropdown, viz_radio],
            outputs=[timeline_output]
        )
        
        # OSS Analysis button - NOW WORKING
        oss_btn.click(
            lambda scenario: run_oss_analysis(scenario),
            inputs=[scenario_dropdown],
            outputs=[results_display]
        )
        
        # Enterprise Execution button - NOW WORKING
        enterprise_btn.click(
            lambda scenario, approval: execute_enterprise_healing(scenario, approval),
            inputs=[scenario_dropdown, approval_toggle],
            outputs=[approval_display, config_display, results_display]
        )
        
        # Approval toggle updates config
        approval_toggle.change(
            lambda approval: {"approval_required": approval, "compliance_mode": "strict"},
            inputs=[approval_toggle],
            outputs=[config_display]
        )
        
        # ROI Calculation - NOW WORKING
        calculate_btn.click(
            calculate_roi,
            inputs=[monthly_slider, impact_slider, team_slider],
            outputs=[roi_output]
        )
        
        # Load initial visualizations
        demo.load(
            lambda: (
                VisualizationEngine.create_business_dashboard(),
                VisualizationEngine.create_execution_history()
            ),
            outputs=[dashboard_output, history_output]
        )
        
        # Refresh audit trail
        refresh_btn.click(
            lambda: VisualizationEngine.create_execution_history(),
            outputs=[history_output]
        )
        
        # Clear audit trail
        clear_btn.click(
            lambda: (
                [],
                VisualizationEngine._create_error_figure("History cleared")
            ),
            outputs=[audit_table, history_output]
        )
    
    return demo

# ===========================================
# LAUNCH APPLICATION
# ===========================================

if __name__ == "__main__":
    logger.info("๐Ÿš€ Launching ARF Investor Demo v3.5.0 - ALL FIXES APPLIED")
    logger.info("โœ… OSS Analysis button: FIXED")
    logger.info("โœ… Enterprise Execution: FIXED")
    logger.info("โœ… ROI Calculator: FIXED")
    logger.info("โœ… All visualizations: WORKING")
    
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=False,
        show_error=True
    )