File size: 41,052 Bytes
3f5fadf
e9fdc7c
ca25698
3f5fadf
 
 
3e4331a
 
859f566
 
5aa5b79
 
9b137fe
3e4331a
9b137fe
7f3d172
859f566
3e4331a
 
 
 
859f566
3e4331a
 
 
fef95f5
 
5aa5b79
859f566
 
ca25698
3e4331a
9b137fe
 
 
 
 
 
5aa5b79
 
ca25698
5aa5b79
9b137fe
5aa5b79
 
 
9b137fe
5aa5b79
 
9b137fe
5aa5b79
 
 
 
 
 
 
 
 
 
 
ca25698
 
 
 
 
 
 
 
 
 
9b137fe
 
 
 
 
 
5aa5b79
9b137fe
5aa5b79
9b137fe
5aa5b79
 
9b137fe
5aa5b79
9b137fe
 
 
 
 
 
 
 
5aa5b79
9b137fe
5aa5b79
9b137fe
 
5aa5b79
9b137fe
 
 
5aa5b79
 
 
 
9b137fe
 
5aa5b79
 
 
 
 
 
 
859f566
5aa5b79
 
9b137fe
5aa5b79
9b137fe
5aa5b79
9b137fe
5aa5b79
 
 
 
 
 
 
 
 
 
 
 
 
ca25698
 
 
 
 
 
 
 
 
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
ca25698
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
9b137fe
 
 
5aa5b79
9b137fe
5aa5b79
 
 
 
9b137fe
5aa5b79
 
 
 
 
9b137fe
5aa5b79
 
ca25698
 
 
 
 
 
 
 
 
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
ca25698
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca25698
 
 
 
 
 
 
 
 
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
ca25698
9b137fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
 
 
 
ca25698
5aa5b79
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
9b137fe
ca25698
 
 
 
859f566
ca25698
 
859f566
ca25698
 
 
 
 
 
859f566
ca25698
 
 
 
9b137fe
ca25698
 
 
 
859f566
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859f566
9b137fe
ca25698
 
9b137fe
 
 
ca25698
 
9b137fe
ca25698
9b137fe
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b137fe
 
 
 
 
ca25698
5aa5b79
 
ca25698
5aa5b79
 
 
ca25698
 
5aa5b79
ca25698
5aa5b79
ca25698
 
 
 
9b137fe
ca25698
 
5aa5b79
ca25698
 
 
 
9b137fe
 
 
ca25698
 
5aa5b79
 
 
9b137fe
859f566
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
9b137fe
5aa5b79
 
ca25698
5aa5b79
9b137fe
ca25698
 
 
 
 
 
 
 
 
9b137fe
ca25698
 
 
 
 
 
 
 
9b137fe
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b137fe
ca25698
 
 
 
 
 
859f566
ca25698
5aa5b79
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
ca25698
5aa5b79
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
9b137fe
ca25698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5aa5b79
ca25698
5aa5b79
ca25698
5aa5b79
9b137fe
 
ca25698
 
 
 
 
 
 
 
 
9b137fe
5aa5b79
ca25698
5aa5b79
 
ca25698
9b137fe
ca25698
 
859f566
5aa5b79
 
 
 
9b137fe
ca25698
5aa5b79
859f566
ca25698
 
 
 
 
5aa5b79
 
ca25698
 
 
 
 
859f566
ca25698
d265a89
ca25698
 
 
 
5aa5b79
 
ca25698
 
 
d265a89
ca25698
 
 
 
5aa5b79
 
ca25698
5aa5b79
ca25698
 
5aa5b79
d265a89
 
 
5aa5b79
9b137fe
5aa5b79
3e4331a
9b137fe
859f566
 
ca25698
 
 
 
 
859f566
5aa5b79
859f566
 
9b137fe
 
 
 
 
d265a89
 
3e4331a
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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
"""
๐Ÿš€ ARF Ultimate Investor Demo v3.8.0 - ENTERPRISE EDITION
UPDATED: Scenario-integrated ROI Calculator + MCP Mode explanations
"""

import logging
import sys
import traceback
import json
import datetime
import asyncio
import time
import numpy as np
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(sys.stdout),
        logging.FileHandler('arf_demo.log')
    ]
)
logger = logging.getLogger(__name__)

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent))

# Import Plotly
try:
    import plotly.graph_objects as go
    import plotly.express as px
    from plotly.subplots import make_subplots
    PLOTLY_AVAILABLE = True
except ImportError:
    PLOTLY_AVAILABLE = False

# ===========================================
# ENHANCED SCENARIOS WITH ROI CALCULATION DATA
# ===========================================
ENHANCED_SCENARIOS = {
    "Cache Miss Storm": {
        "description": "Redis cluster experiencing 80% cache miss rate causing database overload",
        "severity": "CRITICAL",
        "component": "redis_cache",
        "metrics": {
            "Cache Hit Rate": "18.5% (Critical)",
            "Database Load": "92% (Overloaded)",
            "Response Time": "1850ms (Slow)",
            "Affected Users": "45,000",
            "Eviction Rate": "125/sec"
        },
        "impact": {
            "Revenue Loss": "$8,500/hour",
            "Page Load Time": "+300%",
            "Users Impacted": "45,000",
            "SLA Violation": "Yes",
            "Customer Sat": "-40%"
        },
        # ROI CALCULATION DATA (Extracted for calculator)
        "roi_data": {
            "hourly_revenue_loss": 8500,
            "manual_recovery_hours": 1.0,  # 60 minutes
            "enterprise_recovery_hours": 0.2,  # 12 minutes
            "engineers_required": 4,  # 2-3 SREs + 1 DBA
            "engineer_hourly_rate": 150,  # $150/hour
            "estimated_monthly_occurrences": 2,  # Happens twice monthly on average
            "enterprise_savings_percentage": 0.85  # 85% savings with Enterprise
        },
        # OSS RESULTS - ADVISORY ONLY
        "oss_results": {
            "status": "โœ… OSS Analysis Complete",
            "confidence": 0.87,
            "similar_incidents": 3,
            "rag_similarity_score": 0.72,
            "recommendations": [
                "Scale Redis cache memory from 4GB โ†’ 8GB",
                "Implement cache warming strategy",
                "Optimize key patterns with TTL adjustments",
                "Add circuit breaker for database fallback"
            ],
            "estimated_time": "60+ minutes manually",
            "engineers_needed": "2-3 SREs + 1 DBA",
            "advisory_only": True,
            "healing_intent": {
                "action": "scale_out",
                "component": "redis_cache",
                "parameters": {"scale_factor": 2.0},
                "confidence": 0.87,
                "requires_enterprise": True
            }
        },
        # ENTERPRISE RESULTS - ACTUAL EXECUTION
        "enterprise_results": {
            "execution_mode": "Autonomous",
            "actions_executed": [
                "โœ… Auto-scaled Redis cluster: 4GB โ†’ 8GB",
                "โœ… Deployed intelligent cache warming service",
                "โœ… Optimized 12 key patterns with ML recommendations",
                "โœ… Implemented circuit breaker with 95% success rate"
            ],
            "metrics_improvement": {
                "Cache Hit Rate": "18.5% โ†’ 72%",
                "Response Time": "1850ms โ†’ 450ms",
                "Database Load": "92% โ†’ 45%",
                "Throughput": "1250 โ†’ 2450 req/sec"
            },
            "business_impact": {
                "Recovery Time": "60 min โ†’ 12 min",
                "Cost Saved": "$7,200",
                "Users Impacted": "45,000 โ†’ 0",
                "Revenue Protected": "$1,700",
                "MTTR Improvement": "80% reduction"
            }
        }
    },
    
    "Database Connection Pool Exhaustion": {
        "description": "PostgreSQL connection pool exhausted causing API timeouts",
        "severity": "HIGH",
        "component": "postgresql_database",
        "metrics": {
            "Active Connections": "98/100 (Critical)",
            "API Latency": "2450ms",
            "Error Rate": "15.2%",
            "Queue Depth": "1250",
            "Connection Wait": "45s"
        },
        "impact": {
            "Revenue Loss": "$4,200/hour",
            "Affected Services": "API Gateway, User Service, Payment",
            "SLA Violation": "Yes",
            "Partner Impact": "3 external APIs"
        },
        "roi_data": {
            "hourly_revenue_loss": 4200,
            "manual_recovery_hours": 0.75,  # 45 minutes
            "enterprise_recovery_hours": 0.13,  # 8 minutes
            "engineers_required": 2,  # 1 DBA + 1 Backend Engineer
            "engineer_hourly_rate": 150,
            "estimated_monthly_occurrences": 3,
            "enterprise_savings_percentage": 0.82
        },
        "oss_results": {
            "status": "โœ… OSS Analysis Complete",
            "confidence": 0.82,
            "similar_incidents": 2,
            "rag_similarity_score": 0.65,
            "recommendations": [
                "Increase connection pool size from 100 โ†’ 200",
                "Implement connection pooling monitoring",
                "Add query timeout enforcement",
                "Deploy read replica for read-heavy queries"
            ],
            "estimated_time": "45+ minutes manually",
            "engineers_needed": "1 DBA + 1 Backend Engineer",
            "advisory_only": True
        },
        "enterprise_results": {
            "execution_mode": "Approval Required",
            "actions_executed": [
                "โœ… Increased connection pool: 100 โ†’ 200 connections",
                "โœ… Deployed real-time connection monitoring",
                "โœ… Implemented query timeout: 30s โ†’ 10s",
                "โœ… Automated read replica traffic routing"
            ],
            "metrics_improvement": {
                "API Latency": "2450ms โ†’ 320ms",
                "Error Rate": "15.2% โ†’ 0.8%",
                "Connection Wait": "45s โ†’ 120ms",
                "Throughput": "850 โ†’ 2100 req/sec"
            },
            "business_impact": {
                "Recovery Time": "45 min โ†’ 8 min",
                "Cost Saved": "$3,150",
                "Failed Transactions": "12,500 โ†’ 0",
                "SLA Compliance": "Restored to 99.9%"
            }
        }
    },
    
    "Kubernetes Memory Leak": {
        "description": "Java microservice memory leak causing pod restarts",
        "severity": "HIGH",
        "component": "java_payment_service",
        "metrics": {
            "Memory Usage": "96% (Critical)",
            "GC Pause Time": "4500ms",
            "Error Rate": "28.5%",
            "Pod Restarts": "12/hour",
            "Heap Fragmentation": "42%"
        },
        "impact": {
            "Revenue Loss": "$5,500/hour",
            "Session Loss": "8,500 users",
            "Payment Failures": "3.2% of transactions",
            "Support Tickets": "+300%"
        },
        "roi_data": {
            "hourly_revenue_loss": 5500,
            "manual_recovery_hours": 1.5,  # 90 minutes
            "enterprise_recovery_hours": 0.25,  # 15 minutes
            "engineers_required": 3,  # 2 Java Devs + 1 SRE
            "engineer_hourly_rate": 150,
            "estimated_monthly_occurrences": 1,
            "enterprise_savings_percentage": 0.79
        },
        "oss_results": {
            "status": "โœ… OSS Analysis Complete",
            "confidence": 0.79,
            "similar_incidents": 4,
            "rag_similarity_score": 0.68,
            "recommendations": [
                "Increase pod memory limits from 2GB โ†’ 4GB",
                "Implement memory leak detection",
                "Deploy canary with fixed version",
                "Add circuit breaker for graceful degradation"
            ],
            "estimated_time": "90+ minutes manually",
            "engineers_needed": "2 Java Devs + 1 SRE",
            "advisory_only": True
        },
        "enterprise_results": {
            "execution_mode": "Autonomous with Rollback",
            "actions_executed": [
                "โœ… Scaled pod memory: 2GB โ†’ 4GB with monitoring",
                "โœ… Deployed memory leak detection service",
                "โœ… Rolled out canary with memory fixes",
                "โœ… Implemented auto-rollback on failure"
            ],
            "metrics_improvement": {
                "Memory Usage": "96% โ†’ 68%",
                "GC Pause Time": "4500ms โ†’ 320ms",
                "Error Rate": "28.5% โ†’ 1.2%",
                "Pod Stability": "12/hour โ†’ 0 restarts"
            },
            "business_impact": {
                "Recovery Time": "90 min โ†’ 15 min",
                "Cost Saved": "$4,950",
                "Transaction Success": "96.8% โ†’ 99.9%",
                "User Impact": "8,500 โ†’ 0 affected"
            }
        }
    },
    
    "API Rate Limit Storm": {
        "description": "Third-party API rate limiting causing cascading failures",
        "severity": "MEDIUM",
        "component": "external_api_gateway",
        "metrics": {
            "Rate Limit Hits": "95% of requests",
            "Error Rate": "42.8%",
            "Retry Storm": "Active",
            "Cascade Effect": "3 dependent services",
            "Queue Backlog": "8,500 requests"
        },
        "impact": {
            "Revenue Loss": "$3,800/hour",
            "Partner SLA Breach": "Yes",
            "Data Sync Delay": "4+ hours",
            "Customer Reports": "Delayed by 6 hours"
        },
        "roi_data": {
            "hourly_revenue_loss": 3800,
            "manual_recovery_hours": 1.25,  # 75 minutes
            "enterprise_recovery_hours": 0.17,  # 10 minutes
            "engineers_required": 3,  # 2 Backend Engineers + 1 DevOps
            "engineer_hourly_rate": 150,
            "estimated_monthly_occurrences": 4,
            "enterprise_savings_percentage": 0.85
        },
        "oss_results": {
            "status": "โœ… OSS Analysis Complete",
            "confidence": 0.85,
            "similar_incidents": 3,
            "rag_similarity_score": 0.71,
            "recommendations": [
                "Implement exponential backoff with jitter",
                "Deploy circuit breaker pattern",
                "Add request queuing with prioritization",
                "Implement adaptive rate limiting"
            ],
            "estimated_time": "75+ minutes manually",
            "engineers_needed": "2 Backend Engineers + 1 DevOps",
            "advisory_only": True
        },
        "enterprise_results": {
            "execution_mode": "Autonomous",
            "actions_executed": [
                "โœ… Implemented exponential backoff: 1s โ†’ 32s with jitter",
                "โœ… Deployed circuit breaker with 80% success threshold",
                "โœ… Added intelligent request queuing",
                "โœ… Enabled adaptive rate limiting based on API health"
            ],
            "metrics_improvement": {
                "Rate Limit Hits": "95% โ†’ 12%",
                "Error Rate": "42.8% โ†’ 3.5%",
                "Successful Retries": "18% โ†’ 89%",
                "Queue Processing": "8,500 โ†’ 0 backlog"
            },
            "business_impact": {
                "Recovery Time": "75 min โ†’ 10 min",
                "Cost Saved": "$3,420",
                "SLA Compliance": "Restored within 5 minutes",
                "Data Freshness": "4+ hours โ†’ <5 minute delay"
            }
        }
    }
}

# ===========================================
# MCP MODE EXPLANATIONS
# ===========================================
MCP_MODE_DESCRIPTIONS = {
    "advisory": {
        "name": "Advisory Mode",
        "icon": "๐Ÿ“‹",
        "description": "OSS Edition - Analysis only, no execution",
        "purpose": "Analyzes incidents and provides recommendations. Perfect for teams starting with AI reliability.",
        "features": [
            "โœ… Incident detection & analysis",
            "โœ… RAG similarity search",
            "โœ… HealingIntent creation",
            "โŒ No action execution",
            "โŒ Manual implementation required"
        ],
        "use_case": "Compliance-heavy environments, initial AI adoption phases"
    },
    "approval": {
        "name": "Approval Mode",
        "icon": "๐Ÿ”",
        "description": "Enterprise - Executes after human approval",
        "purpose": "Balances automation with human oversight. Actions require explicit approval before execution.",
        "features": [
            "โœ… All OSS advisory features",
            "โœ… Action execution capability",
            "โœ… Human-in-the-loop approval",
            "โœ… Audit trail & compliance",
            "โœ… Rollback capabilities"
        ],
        "use_case": "Regulated industries, critical production systems"
    },
    "autonomous": {
        "name": "Autonomous Mode",
        "icon": "โšก",
        "description": "Enterprise - Fully autonomous execution",
        "purpose": "Maximum efficiency with AI-driven autonomous healing. Self-corrects based on learned patterns.",
        "features": [
            "โœ… All approval mode features",
            "โœ… Fully autonomous execution",
            "โœ… Machine learning optimization",
            "โœ… Predictive incident prevention",
            "โœ… Continuous learning loop"
        ],
        "use_case": "High-scale systems, mature reliability teams, 24/7 operations"
    }
}

# ===========================================
# ROI CALCULATOR ENGINE
# ===========================================
class ROI_Calculator:
    """Calculates ROI based on scenario data and user inputs"""
    
    @staticmethod
    def calculate_scenario_roi(scenario_name, monthly_incidents, team_size):
        """Calculate ROI for a specific scenario"""
        scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
        roi_data = scenario.get("roi_data", {})
        
        if not roi_data:
            return {"error": "No ROI data for this scenario"}
        
        # Extract data
        hourly_loss = roi_data.get("hourly_revenue_loss", 0)
        manual_hours = roi_data.get("manual_recovery_hours", 1)
        enterprise_hours = roi_data.get("enterprise_recovery_hours", 0.2)
        monthly_occurrences = roi_data.get("estimated_monthly_occurrences", 2)
        savings_pct = roi_data.get("enterprise_savings_percentage", 0.85)
        
        # Calculate costs
        monthly_manual_cost = hourly_loss * manual_hours * monthly_occurrences
        monthly_enterprise_cost = hourly_loss * enterprise_hours * monthly_occurrences
        monthly_savings = monthly_manual_cost - monthly_enterprise_cost
        
        # Annual calculations
        annual_manual_cost = monthly_manual_cost * 12
        annual_enterprise_cost = monthly_enterprise_cost * 12
        annual_savings = monthly_savings * 12
        
        # Team costs
        engineer_hourly = roi_data.get("engineer_hourly_rate", 150)
        engineers_needed = roi_data.get("engineers_required", 2)
        team_hourly_cost = engineers_needed * engineer_hourly
        manual_team_cost = team_hourly_cost * manual_hours * monthly_occurrences * 12
        
        # Enterprise subscription (simplified)
        enterprise_monthly_cost = 499  # Base subscription
        enterprise_usage_cost = monthly_enterprise_cost * 0.10  # $0.10 per incident
        
        # ROI calculation
        total_enterprise_cost = (enterprise_monthly_cost * 12) + (enterprise_usage_cost * 12)
        roi_multiplier = annual_savings / total_enterprise_cost if total_enterprise_cost > 0 else 0
        payback_months = total_enterprise_cost / (annual_savings / 12) if annual_savings > 0 else 0
        
        return {
            "scenario": scenario_name,
            "monthly_manual_cost": f"${monthly_manual_cost:,.0f}",
            "monthly_enterprise_cost": f"${monthly_enterprise_cost:,.0f}",
            "monthly_savings": f"${monthly_savings:,.0f}",
            "annual_manual_cost": f"${annual_manual_cost:,.0f}",
            "annual_enterprise_cost": f"${annual_enterprise_cost:,.0f}",
            "annual_savings": f"${annual_savings:,.0f}",
            "enterprise_subscription": f"${enterprise_monthly_cost:,.0f}/month",
            "roi_multiplier": f"{roi_multiplier:.1f}ร—",
            "payback_months": f"{payback_months:.1f} months",
            "manual_recovery_time": f"{manual_hours*60:.0f} minutes",
            "enterprise_recovery_time": f"{enterprise_hours*60:.0f} minutes",
            "recovery_improvement": f"{(1 - enterprise_hours/manual_hours)*100:.0f}% faster"
        }
    
    @staticmethod
    def create_comparison_chart(scenario_name):
        """Create ROI comparison chart"""
        if not PLOTLY_AVAILABLE:
            return None
        
        scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
        roi_data = scenario.get("roi_data", {})
        
        fig = go.Figure()
        
        # Manual vs Enterprise cost comparison
        manual_cost = roi_data.get("hourly_revenue_loss", 0) * roi_data.get("manual_recovery_hours", 1)
        enterprise_cost = roi_data.get("hourly_revenue_loss", 0) * roi_data.get("enterprise_recovery_hours", 0.2)
        
        fig.add_trace(go.Bar(
            x=['Manual Resolution', 'ARF Enterprise'],
            y=[manual_cost, enterprise_cost],
            name='Cost per Incident',
            marker_color=['#FF6B6B', '#4ECDC4'],
            text=[f'${manual_cost:,.0f}', f'${enterprise_cost:,.0f}'],
            textposition='auto'
        ))
        
        fig.update_layout(
            title=f"Cost Comparison: {scenario_name}",
            yaxis_title="Cost ($)",
            showlegend=False,
            height=300
        )
        
        return fig

# ===========================================
# CREATE DEMO INTERFACE WITH ENHANCEMENTS
# ===========================================
def create_demo_interface():
    """Create demo with scenario-integrated ROI calculator and MCP explanations"""
    
    import gradio as gr
    
    # Initialize
    roi_calculator = ROI_Calculator()
    
    # Custom CSS for enhancements
    custom_css = """
    .mcp-mode-card {
        background: white !important;
        border-radius: 10px !important;
        padding: 20px !important;
        margin-bottom: 15px !important;
        border-left: 4px solid #4ECDC4 !important;
        box-shadow: 0 2px 8px rgba(0,0,0,0.06) !important;
    }
    .mcp-advisory { border-left-color: #2196f3 !important; }
    .mcp-approval { border-left-color: #ff9800 !important; }
    .mcp-autonomous { border-left-color: #4caf50 !important; }
    .roi-highlight {
        background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%) !important;
        padding: 15px !important;
        border-radius: 8px !important;
        border-left: 4px solid #4caf50 !important;
        margin: 10px 0 !important;
    }
    """
    
    with gr.Blocks(title="๐Ÿš€ ARF Investor Demo v3.8.0", css=custom_css) as demo:
        
        # Header
        gr.Markdown("""
        <div style="text-align: center; padding: 30px 20px 20px 20px; background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%); border-radius: 0 0 20px 20px; margin-bottom: 30px; border-bottom: 3px solid #4ECDC4;">
            <h1 style="margin-bottom: 10px;">๐Ÿš€ Agentic Reliability Framework</h1>
            <h2 style="color: #4a5568; font-weight: 600; margin-bottom: 20px;">Investor Demo v3.8.0</h2>
            
            <div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap; margin-bottom: 20px;">
                <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 8px 16px; border-radius: 20px; font-weight: 700; font-size: 0.85rem;">
                    ๐Ÿข Enterprise Edition
                </div>
                <div style="background: linear-gradient(135deg, #4299e1 0%, #38b2ac 100%); color: white; padding: 8px 16px; border-radius: 20px; font-weight: 700; font-size: 0.85rem;">
                    ๐Ÿ†“ OSS v3.3.6
                </div>
                <div style="background: #e8f5e8; color: #2d3748; padding: 8px 16px; border-radius: 20px; font-weight: 600; font-size: 0.85rem;">
                    ๐Ÿ“ˆ 5.2ร— ROI
                </div>
                <div style="background: #fff3cd; color: #856404; padding: 8px 16px; border-radius: 20px; font-weight: 600; font-size: 0.85rem;">
                    โšก 85% MTTR Reduction
                </div>
            </div>
            
            <div style="color: #718096; font-size: 16px; max-width: 800px; margin: 0 auto; line-height: 1.6;">
                From <span style="font-weight: 700; color: #4299e1;">OSS Advisory</span> 
                to <span style="font-weight: 700; color: #764ba2;">Enterprise Autonomous Healing</span>.
                <span style="color: #4ECDC4; font-weight: 600;"> New: Scenario-integrated ROI Calculator</span>
            </div>
            
            <div style="margin-top: 15px; font-size: 0.9rem; color: #FFA726; font-weight: 600;">
                โš ๏ธ Mock Mode (Enhanced ROI Calculator)
            </div>
        </div>
        """)
        
        # Status Bar
        gr.Markdown("""
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 25px;">
            <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border-left: 4px solid #4ECDC4;">
                <div style="font-size: 0.9rem; color: #718096; margin-bottom: 5px;">System Status</div>
                <div style="display: flex; align-items: center; gap: 8px;">
                    <div style="width: 10px; height: 10px; background: #4ECDC4; border-radius: 50%;"></div>
                    <div style="font-weight: 700; color: #2d3748;">Operational</div>
                </div>
            </div>
            
            <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border-left: 4px solid #FFA726;">
                <div style="font-size: 0.9rem; color: #718096; margin-bottom: 5px;">Active Scenario</div>
                <div style="font-weight: 700; color: #2d3748; font-size: 1.1rem;">Cache Miss Storm</div>
            </div>
            
            <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.06); border-left: 4px solid #42A5F5;">
                <div style="font-size: 0.9rem; color: #718096; margin-bottom: 5px;">MCP Mode</div>
                <div style="font-weight: 700; color: #2d3748; font-size: 1.1rem;">Advisory (OSS)</div>
            </div>
        </div>
        """)
        
        # Tabs
        with gr.Tabs():
            
            # TAB 1: Live Incident Demo
            with gr.TabItem("๐Ÿ”ฅ Live Incident Demo"):
                with gr.Row():
                    # Left Panel
                    with gr.Column(scale=1):
                        gr.Markdown("### ๐ŸŽฌ Select Incident Scenario")
                        
                        scenario_dropdown = gr.Dropdown(
                            choices=list(ENHANCED_SCENARIOS.keys()),
                            value="Cache Miss Storm",
                            label="Choose an incident to analyze:",
                            interactive=True
                        )
                        
                        scenario_description = gr.Markdown()
                        
                        gr.Markdown("### ๐Ÿ“Š Current Metrics")
                        metrics_display = gr.JSON(label="")
                        
                        gr.Markdown("### ๐Ÿ’ฐ Business Impact")
                        impact_display = gr.JSON(label="")
                    
                    # Right Panel
                    with gr.Column(scale=2):
                        gr.Markdown("### ๐Ÿ“ˆ Incident Timeline")
                        timeline_output = gr.Plot()
                        
                        gr.Markdown("### โšก Take Action")
                        with gr.Row():
                            oss_btn = gr.Button("๐Ÿ†“ Run OSS Analysis", variant="secondary", size="lg")
                            enterprise_btn = gr.Button("๐Ÿš€ Execute Enterprise Healing", variant="primary", size="lg")
                        
                        with gr.Row():
                            approval_toggle = gr.Checkbox(label="๐Ÿ” Require Manual Approval", value=True)
                            demo_btn = gr.Button("โšก Quick Demo", variant="secondary", size="sm")
                        
                        approval_display = gr.HTML(
                            value="<div style='padding: 15px; background: #f8f9fa; border-radius: 8px; color: #6c757d;'>Approval workflow will appear here after execution</div>"
                        )
                        
                        gr.Markdown("### ๐Ÿ“‹ OSS Analysis Results (Advisory Only)")
                        oss_results = gr.JSON(label="")
                        
                        gr.Markdown("### ๐ŸŽฏ Enterprise Execution Results")
                        enterprise_results = gr.JSON(label="")
            
            # TAB 2: Business Impact & ROI (ENHANCED)
            with gr.TabItem("๐Ÿ’ฐ Business Impact & ROI"):
                with gr.Column():
                    gr.Markdown("### ๐Ÿ“Š Executive Dashboard")
                    dashboard_output = gr.Plot()
                    
                    gr.Markdown("### ๐Ÿงฎ ROI Calculator (Scenario-Integrated)")
                    with gr.Row():
                        with gr.Column(scale=1):
                            # Scenario selector for ROI
                            roi_scenario_dropdown = gr.Dropdown(
                                choices=list(ENHANCED_SCENARIOS.keys()),
                                value="Cache Miss Storm",
                                label="Select scenario for ROI calculation:",
                                interactive=True
                            )
                            
                            gr.Markdown("#### ๐Ÿ“ˆ Adjust Parameters")
                            monthly_slider = gr.Slider(
                                1, 100, value=15, step=1,
                                label="Monthly similar incidents:",
                                info="How often this type of incident occurs",
                                interactive=True
                            )
                            
                            team_slider = gr.Slider(
                                1, 20, value=5, step=1,
                                label="Reliability team size:",
                                info="Engineers available for manual resolution",
                                interactive=True
                            )
                            
                            calculate_roi_btn = gr.Button(
                                "Calculate Scenario ROI",
                                variant="primary",
                                size="lg"
                            )
                            
                            # Show scenario data being used
                            gr.Markdown("#### ๐Ÿ“Š Using Scenario Data:")
                            scenario_data_display = gr.JSON(
                                label="Extracted from selected scenario",
                                value={}
                            )
                        
                        with gr.Column(scale=2):
                            gr.Markdown("#### ๐Ÿ“ˆ ROI Analysis Results")
                            roi_output = gr.JSON(label="")
                            
                            gr.Markdown("#### ๐Ÿ“Š Cost Comparison")
                            roi_chart = gr.Plot(label="")
                            
                            # Highlight key metrics
                            gr.Markdown("""
                            <div class="roi-highlight">
                                <h4 style="margin: 0 0 10px 0;">๐Ÿ’ฐ Key Insight</h4>
                                <p style="margin: 0;">The ROI calculator now extracts real numbers from your selected incident scenario, showing the actual business impact of ARF Enterprise vs manual resolution.</p>
                            </div>
                            """)
            
            # TAB 4: Enterprise Features (ENHANCED WITH MCP EXPLANATIONS)
            with gr.TabItem("๐Ÿข Enterprise Features"):
                with gr.Row():
                    # Left Column
                    with gr.Column(scale=1):
                        gr.Markdown("### ๐Ÿ” License Management")
                        
                        license_display = gr.JSON(
                            value={
                                "status": "Active",
                                "tier": "Enterprise",
                                "expires": "2024-12-31",
                                "mcp_mode": "advisory"
                            },
                            label="Current License"
                        )
                        
                        gr.Markdown("### โšก MCP Execution Modes")
                        
                        # MCP Mode Cards with explanations
                        for mode_key, mode_info in MCP_MODE_DESCRIPTIONS.items():
                            with gr.Column():
                                gr.Markdown(f"""
                                <div class="mcp-mode-card mcp-{mode_key}">
                                    <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
                                        <div style="font-size: 1.5rem;">{mode_info['icon']}</div>
                                        <div>
                                            <h4 style="margin: 0;">{mode_info['name']}</h4>
                                            <div style="font-size: 0.9rem; color: #718096;">{mode_info['description']}</div>
                                        </div>
                                    </div>
                                    <div style="margin-bottom: 10px;">
                                        <strong>Purpose:</strong> {mode_info['purpose']}
                                    </div>
                                    <div>
                                        <strong>Best for:</strong> {mode_info['use_case']}
                                    </div>
                                </div>
                                """)
                        
                        # MCP Mode Selector
                        gr.Markdown("### โš™๏ธ Configure MCP Mode")
                        mcp_mode = gr.Radio(
                            choices=list(MCP_MODE_DESCRIPTIONS.keys()),
                            value="advisory",
                            label="Execution Mode",
                            info="Select the execution mode for demonstration",
                            interactive=True
                        )
                        
                        mcp_mode_info = gr.JSON(
                            label="Selected Mode Details",
                            value=MCP_MODE_DESCRIPTIONS["advisory"]
                        )
                    
                    # Right Column
                    with gr.Column(scale=1):
                        gr.Markdown("### ๐Ÿ“‹ Feature Comparison")
                        
                        features_table = gr.Dataframe(
                            headers=["Feature", "OSS", "Starter", "Enterprise"],
                            value=[
                                ["Autonomous Healing", "โŒ", "โœ… Auto", "โœ… AI-Driven"],
                                ["MCP Modes", "Advisory only", "Advisory + Approval", "All 3 modes"],
                                ["Compliance Automation", "โŒ", "โœ…", "โœ… SOC2/GDPR"],
                                ["Predictive Analytics", "โŒ", "Basic", "โœ… ML-Powered"],
                                ["Multi-Cloud Support", "โŒ", "โŒ", "โœ… Native"],
                                ["Audit Trail", "Basic", "โœ…", "โœ… Comprehensive"],
                                ["Role-Based Access", "โŒ", "โœ…", "โœ… Granular"],
                            ],
                            label="",
                            interactive=False
                        )
                        
                        gr.Markdown("### ๐Ÿ”— Integrations")
                        
                        integrations_table = gr.Dataframe(
                            headers=["Platform", "Status", "Last Sync"],
                            value=[
                                ["AWS", "โœ… Connected", "5 min ago"],
                                ["Azure", "โœ… Connected", "8 min ago"],
                                ["GCP", "โœ… Connected", "3 min ago"],
                                ["Datadog", "โœ… Connected", "Active"],
                                ["PagerDuty", "โœ… Connected", "Active"],
                                ["ServiceNow", "โœ… Connected", "15 min ago"],
                            ],
                            label="",
                            interactive=False
                        )
            
            # Other tabs...
            with gr.TabItem("๐Ÿ“œ Audit Trail & History"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### ๐Ÿ“‹ Execution History")
                        execution_table = gr.Dataframe(
                            headers=["Time", "Scenario", "Mode", "Status", "Savings", "Details"],
                            value=[],
                            label=""
                        )
                    
                    with gr.Column():
                        gr.Markdown("### ๐Ÿ“Š Incident History")
                        incident_table = gr.Dataframe(
                            headers=["Time", "Component", "Scenario", "Severity", "Status"],
                            value=[],
                            label=""
                        )
        
        # Footer
        gr.Markdown("""
        <div style="margin-top: 40px; padding: 30px; background: linear-gradient(135deg, #1a365d 0%, #2d3748 100%); border-radius: 20px; color: white;">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 30px; margin-bottom: 30px;">
                <div>
                    <h4 style="color: white; margin-bottom: 15px;">๐Ÿš€ User Journey</h4>
                    <ol style="color: #cbd5e0; padding-left: 20px;">
                        <li style="margin-bottom: 8px;">1. Select Incident Scenario</li>
                        <li style="margin-bottom: 8px;">2. Calculate Scenario-specific ROI</li>
                        <li style="margin-bottom: 8px;">3. Execute Enterprise Healing</li>
                        <li style="margin-bottom: 8px;">4. Compare MCP Execution Modes</li>
                        <li>5. Explore Audit Trail</li>
                    </ol>
                </div>
                
                <div>
                    <h4 style="color: white; margin-bottom: 15px;">๐Ÿ“ž Get Started</h4>
                    <ul style="color: #cbd5e0; list-style: none; padding: 0;">
                        <li style="margin-bottom: 8px;">๐Ÿ“ง sales@arfinvestor.com</li>
                        <li style="margin-bottom: 8px;">๐Ÿ“š docs.arfinvestor.com</li>
                        <li style="margin-bottom: 8px;">๐Ÿ’ฌ Join Slack Community</li>
                        <li>๐Ÿ†“ 30-Day Enterprise Trial</li>
                    </ul>
                </div>
                
                <div>
                    <h4 style="color: white; margin-bottom: 15px;">๐Ÿ›ก๏ธ Enterprise Grade</h4>
                    <ul style="color: #cbd5e0; list-style: none; padding: 0;">
                        <li style="margin-bottom: 8px;">โœ… SOC 2 Type II</li>
                        <li style="margin-bottom: 8px;">โœ… GDPR & CCPA</li>
                        <li style="margin-bottom: 8px;">โœ… ISO 27001</li>
                        <li>โœ… HIPAA Ready</li>
                    </ul>
                </div>
            </div>
            
            <div style="border-top: 1px solid #4a5568; padding-top: 20px; text-align: center; color: #a0aec0; font-size: 0.9rem;">
                <p style="margin: 0;">ยฉ 2024 Agentic Reliability Framework. Demo v3.8.0 Enterprise Edition.</p>
                <p style="margin: 10px 0 0 0; font-size: 0.8rem;">Enhanced with scenario-integrated ROI calculator and MCP mode explanations</p>
            </div>
        </div>
        """)
        
        # ============ EVENT HANDLERS ============
        
        # Update scenario (enhanced with ROI data)
        def update_scenario(scenario_name):
            scenario = ENHANCED_SCENARIOS.get(scenario_name, {})
            
            # Extract ROI data for display
            roi_data = scenario.get("roi_data", {})
            display_roi_data = {
                "Hourly Revenue Loss": f"${roi_data.get('hourly_revenue_loss', 0):,.0f}",
                "Manual Recovery Time": f"{roi_data.get('manual_recovery_hours', 1)*60:.0f} minutes",
                "Enterprise Recovery Time": f"{roi_data.get('enterprise_recovery_hours', 0.2)*60:.0f} minutes",
                "Monthly Occurrences": roi_data.get("estimated_monthly_occurrences", 2),
                "Engineers Required": roi_data.get("engineers_required", 2)
            }
            
            return (
                f"### {scenario_name}\n{scenario.get('description', '')}",
                scenario.get("metrics", {}),
                scenario.get("impact", {}),
                None,  # Placeholder for timeline
                {},  # Clear OSS results
                {},  # Clear Enterprise results
                display_roi_data
            )
        
        scenario_dropdown.change(
            fn=update_scenario,
            inputs=[scenario_dropdown],
            outputs=[scenario_description, metrics_display, impact_display,
                    timeline_output, oss_results, enterprise_results, scenario_data_display]
        )
        
        # Update ROI scenario dropdown
        roi_scenario_dropdown.change(
            fn=lambda name: ENHANCED_SCENARIOS.get(name, {}).get("roi_data", {}),
            inputs=[roi_scenario_dropdown],
            outputs=[scenario_data_display]
        )
        
        # Calculate ROI with scenario data
        def calculate_scenario_roi(scenario_name, monthly_incidents, team_size):
            """Calculate ROI using scenario-specific data"""
            roi_result = roi_calculator.calculate_scenario_roi(scenario_name, monthly_incidents, team_size)
            roi_chart_plot = roi_calculator.create_comparison_chart(scenario_name)
            
            return roi_result, roi_chart_plot
        
        calculate_roi_btn.click(
            fn=calculate_scenario_roi,
            inputs=[roi_scenario_dropdown, monthly_slider, team_slider],
            outputs=[roi_output, roi_chart]
        )
        
        # Update MCP mode info
        def update_mcp_mode(mode):
            return MCP_MODE_DESCRIPTIONS.get(mode, {})
        
        mcp_mode.change(
            fn=update_mcp_mode,
            inputs=[mcp_mode],
            outputs=[mcp_mode_info]
        )
        
        # Initialize with first scenario ROI data
        demo.load(
            fn=lambda: ENHANCED_SCENARIOS["Cache Miss Storm"].get("roi_data", {}),
            outputs=[scenario_data_display]
        )
    
    return demo

# ===========================================
# MAIN EXECUTION
# ===========================================
def main():
    """Main entry point"""
    print("๐Ÿš€ Starting ARF Ultimate Investor Demo v3.8.0...")
    print("=" * 70)
    print("๐Ÿ“Š New Features:")
    print("  โ€ข Scenario-integrated ROI Calculator")
    print("  โ€ข Extracts revenue loss from incident scenarios")
    print("  โ€ข MCP Mode explanations with use cases")
    print("  โ€ข 4 Enhanced incident scenarios")
    print("=" * 70)
    print("๐ŸŒ Opening web interface...")
    
    demo = create_demo_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )

if __name__ == "__main__":
    main()