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f227c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
 
f227c8e
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
f227c8e
 
 
bc06c6d
f227c8e
bc06c6d
 
f227c8e
 
 
 
 
 
 
 
 
 
bc06c6d
 
f227c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
 
f227c8e
bc06c6d
f227c8e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
 
f227c8e
bc06c6d
f227c8e
bc06c6d
f227c8e
 
bc06c6d
 
 
f227c8e
 
 
bc06c6d
 
 
 
f227c8e
bc06c6d
f227c8e
 
 
 
 
 
bc06c6d
f227c8e
 
bc06c6d
 
 
f227c8e
 
bc06c6d
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
"""
Hugging Face Spaces Demo for Agentic Reliability Framework (ARF)
Version: 3.3.9 OSS vs Enterprise
Proper import structure based on actual repository
"""

import gradio as gr
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import json
import time
import uuid
from typing import Dict, List, Any, Optional, Tuple
import hashlib
import random
import sys
import traceback

print("=" * 60)
print("πŸ€– ARF 3.3.9 Hugging Face Spaces Demo - Starting")
print("=" * 60)

# Try to import ARF with multiple possible import paths
ARF_AVAILABLE = False
ARF_MODULES = {}

try:
    # Try direct import
    from agentic_reliability_framework.models import (
        ReliabilityEvent,
        HealingPolicy
    )
    from agentic_reliability_framework.healing_policies import PolicyEngine
    from agentic_reliability_framework.engine.reliability import ReliabilityEngine
    from agentic_reliability_framework import __version__
    
    ARF_AVAILABLE = True
    ARF_VERSION = __version__.__version__
    print(f"βœ… ARF {ARF_VERSION} successfully imported")
    
    # Store imported modules
    ARF_MODULES = {
        'ReliabilityEvent': ReliabilityEvent,
        'HealingPolicy': HealingPolicy,
        'PolicyEngine': PolicyEngine,
        'ReliabilityEngine': ReliabilityEngine,
        'version': ARF_VERSION
    }
    
except ImportError as e:
    print(f"⚠️  Import error: {e}")
    print("Creating mock implementations for demo...")
    
    # Create comprehensive mock implementations
    class MockReliabilityEvent:
        def __init__(self, event_id: str, agent_id: str, action: str, 
                    timestamp: datetime, context: Dict = None):
            self.event_id = event_id
            self.agent_id = agent_id
            self.action = action
            self.timestamp = timestamp
            self.context = context or {}
            self.metadata = {"source": "demo", "environment": "testing"}
        
        def to_dict(self) -> Dict:
            return {
                'event_id': self.event_id,
                'agent_id': self.agent_id,
                'action': self.action,
                'timestamp': self.timestamp.isoformat(),
                'context': self.context,
                'metadata': self.metadata
            }
    
    class MockHealingPolicy:
        class PolicyAction:
            ALLOW = "allow"
            HEAL = "heal"
            BLOCK = "block"
            WARN = "warn"
        
        def __init__(self, id: str, name: str, description: str, 
                    conditions: Dict, action: str, priority: int = 1):
            self.id = id
            self.name = name
            self.description = description
            self.conditions = conditions
            self.action = action
            self.priority = priority
            self.created_at = datetime.now()
            self.updated_at = datetime.now()
        
        def evaluate(self, event: 'MockReliabilityEvent', score: float) -> Tuple[bool, str]:
            """Evaluate if policy conditions are met"""
            action_lower = event.action.lower()
            context = event.context
            
            # Check for high-risk patterns
            high_risk_keywords = ['drop database', 'delete from', 'truncate', 'rm -rf', 'format']
            if any(keyword in action_lower for keyword in high_risk_keywords):
                return True, f"High-risk action detected: {event.action}"
            
            # Check for production environment
            if context.get('environment') == 'production' and 'deploy' in action_lower:
                if score < 0.8:
                    return True, f"Low confidence ({score:.2f}) for production deployment"
            
            return False, ""
    
    class MockPolicyEngine:
        def __init__(self):
            self.policies = []
            self.load_default_policies()
        
        def load_default_policies(self):
            """Load default demo policies"""
            self.policies = [
                MockHealingPolicy(
                    id="policy-001",
                    name="High-Risk Database Prevention",
                    description="Prevents irreversible database operations",
                    conditions={"risk_threshold": 0.7},
                    action=MockHealingPolicy.PolicyAction.BLOCK,
                    priority=1
                ),
                MockHealingPolicy(
                    id="policy-002",
                    name="Production Deployment Safety",
                    description="Ensures safe deployments to production",
                    conditions={"confidence_threshold": 0.8, "environment": "production"},
                    action=MockHealingPolicy.PolicyAction.HEAL,
                    priority=2
                ),
                MockHealingPolicy(
                    id="policy-003",
                    name="Sensitive Data Access",
                    description="Controls access to sensitive data",
                    conditions={"data_classification": ["pci", "pii", "phi"]},
                    action=MockHealingPolicy.PolicyAction.WARN,
                    priority=3
                )
            ]
        
        def evaluate(self, event: MockReliabilityEvent, reliability_score: float) -> List[Dict]:
            """Evaluate all policies against event"""
            violations = []
            
            for policy in self.policies:
                triggered, reason = policy.evaluate(event, reliability_score)
                if triggered:
                    violations.append({
                        'policy_id': policy.id,
                        'policy_name': policy.name,
                        'action': policy.action,
                        'reason': reason,
                        'priority': policy.priority
                    })
            
            return violations
    
    class MockReliabilityEngine:
        def __init__(self):
            self.scoring_factors = {
                'syntax_complexity': 0.2,
                'risk_keywords': 0.3,
                'environment_risk': 0.2,
                'historical_safety': 0.2,
                'time_of_day': 0.1
            }
        
        def calculate_score(self, event: MockReliabilityEvent) -> Dict:
            """Calculate reliability score for an event"""
            action = event.action.lower()
            context = event.context
            
            # Calculate individual factors
            syntax_score = self._calculate_syntax_complexity(action)
            risk_score = self._calculate_risk_keywords(action)
            env_score = self._calculate_environment_risk(context)
            historical_score = 0.8  # Default historical safety
            time_score = self._calculate_time_of_day()
            
            # Weighted sum
            overall = (
                syntax_score * self.scoring_factors['syntax_complexity'] +
                risk_score * self.scoring_factors['risk_keywords'] +
                env_score * self.scoring_factors['environment_risk'] +
                historical_score * self.scoring_factors['historical_safety'] +
                time_score * self.scoring_factors['time_of_day']
            )
            
            # Confidence based on factors considered
            confidence = min(0.95, overall * 1.1)  # Slightly optimistic
            
            return {
                'overall': round(overall, 3),
                'confidence': round(confidence, 3),
                'risk_score': round(1 - overall, 3),
                'components': {
                    'syntax_complexity': syntax_score,
                    'risk_keywords': risk_score,
                    'environment_risk': env_score,
                    'historical_safety': historical_score,
                    'time_of_day': time_score
                }
            }
        
        def _calculate_syntax_complexity(self, action: str) -> float:
            """Calculate complexity score based on action syntax"""
            words = len(action.split())
            if words <= 3:
                return 0.9  # Simple commands are safer
            elif words <= 6:
                return 0.7
            else:
                return 0.5  # Complex commands are riskier
        
        def _calculate_risk_keywords(self, action: str) -> float:
            """Calculate risk based on keywords"""
            high_risk = ['drop', 'delete', 'truncate', 'remove', 'format', 'rm']
            medium_risk = ['update', 'alter', 'modify', 'change', 'grant', 'revoke']
            safe = ['select', 'read', 'get', 'fetch', 'list', 'show']
            
            action_lower = action.lower()
            
            for word in high_risk:
                if word in action_lower:
                    return 0.3  # High risk
            
            for word in medium_risk:
                if word in action_lower:
                    return 0.6  # Medium risk
            
            for word in safe:
                if word in action_lower:
                    return 0.9  # Safe
            
            return 0.7  # Default
        
        def _calculate_environment_risk(self, context: Dict) -> float:
            """Calculate risk based on environment"""
            env = context.get('environment', 'development').lower()
            
            env_scores = {
                'production': 0.4,
                'staging': 0.7,
                'testing': 0.8,
                'development': 0.9,
                'sandbox': 0.95
            }
            
            return env_scores.get(env, 0.7)
        
        def _calculate_time_of_day(self) -> float:
            """Calculate risk based on time of day"""
            hour = datetime.now().hour
            
            # Business hours are safer (9 AM - 6 PM)
            if 9 <= hour < 18:
                return 0.9
            elif 18 <= hour < 22:
                return 0.7  # Evening
            else:
                return 0.5  # Night/early morning
    
    # Store mock modules
    ARF_MODULES = {
        'ReliabilityEvent': MockReliabilityEvent,
        'HealingPolicy': MockHealingPolicy,
        'PolicyEngine': MockPolicyEngine,
        'ReliabilityEngine': MockReliabilityEngine,
        'version': '3.3.9 (Mock)'
    }
    
    print("βœ… Mock ARF implementations created successfully")

print("=" * 60)

# Now use ARF_MODULES for all operations
ReliabilityEvent = ARF_MODULES['ReliabilityEvent']
HealingPolicy = ARF_MODULES['HealingPolicy']
PolicyEngine = ARF_MODULES['PolicyEngine']
ReliabilityEngine = ARF_MODULES['ReliabilityEngine']
ARF_VERSION = ARF_MODULES['version']

# Mock Enterprise Components
class MockEnterpriseLicenseManager:
    """Simulates enterprise license validation with mechanical gates"""
    
    def __init__(self):
        self.license_tiers = {
            "trial": {
                "name": "Trial",
                "price": 0,
                "enforcement": "advisory",
                "max_agents": 3,
                "features": ["Basic risk assessment", "7-day trial"],
                "gates_enabled": ["confidence_threshold", "risk_assessment"]
            },
            "starter": {
                "name": "Starter",
                "price": 2000,
                "enforcement": "human_approval",
                "max_agents": 10,
                "features": ["Human-in-loop gates", "Basic audit trail", "Email support"],
                "gates_enabled": ["license_validation", "confidence_threshold", "risk_assessment", "admin_approval"]
            },
            "professional": {
                "name": "Professional",
                "price": 5000,
                "enforcement": "autonomous",
                "max_agents": 50,
                "features": ["Autonomous execution", "Advanced audit", "Priority support", "SLA 99.5%"],
                "gates_enabled": ["license_validation", "confidence_threshold", "risk_assessment", 
                                 "rollback_feasibility", "budget_check", "auto_scale"]
            },
            "enterprise": {
                "name": "Enterprise",
                "price": 15000,
                "enforcement": "full_mechanical",
                "max_agents": 1000,
                "features": ["Full mechanical enforcement", "Compliance automation", 
                           "Custom gates", "24/7 support", "SLA 99.9%", "Differential privacy"],
                "gates_enabled": ["license_validation", "confidence_threshold", "risk_assessment",
                                 "rollback_feasibility", "compliance_check", "budget_check",
                                 "custom_gates", "emergency_override", "audit_logging"]
            }
        }
        
        self.active_licenses = {}
        self._create_demo_licenses()
    
    def _create_demo_licenses(self):
        """Create demo licenses for testing"""
        self.active_licenses = {
            "ARF-TRIAL-DEMO123": {
                "tier": "trial",
                "email": "demo@arf.dev",
                "expires": datetime.now() + timedelta(days=14),
                "created": datetime.now(),
                "features": self.license_tiers["trial"]["features"]
            },
            "ARF-STARTER-456XYZ": {
                "tier": "starter",
                "email": "customer@example.com",
                "expires": datetime.now() + timedelta(days=365),
                "created": datetime.now() - timedelta(days=30),
                "features": self.license_tiers["starter"]["features"]
            },
            "ARF-PRO-789ABC": {
                "tier": "professional",
                "email": "pro@company.com",
                "expires": datetime.now() + timedelta(days=365),
                "created": datetime.now() - timedelta(days=60),
                "features": self.license_tiers["professional"]["features"]
            }
        }
    
    def validate_license(self, license_key: str) -> Dict:
        """Validate enterprise license"""
        if not license_key:
            return {
                "valid": False,
                "tier": "none",
                "enforcement": "none",
                "message": "No license provided - using OSS mode",
                "gates_available": []
            }
        
        license_data = self.active_licenses.get(license_key)
        
        if license_data:
            tier = license_data["tier"]
            tier_info = self.license_tiers[tier]
            
            return {
                "valid": True,
                "tier": tier,
                "name": tier_info["name"],
                "enforcement": tier_info["enforcement"],
                "gates_available": tier_info["gates_enabled"],
                "features": tier_info["features"],
                "expires": license_data["expires"].strftime("%Y-%m-%d"),
                "message": f"{tier_info['name']} license active"
            }
        
        # Check if it's a trial license pattern
        if license_key.startswith("ARF-TRIAL-"):
            return {
                "valid": True,
                "tier": "trial",
                "name": "Trial",
                "enforcement": "advisory",
                "gates_available": self.license_tiers["trial"]["gates_enabled"],
                "features": self.license_tiers["trial"]["features"],
                "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
                "message": "Trial license activated (14 days)"
            }
        
        return {
            "valid": False,
            "tier": "invalid",
            "enforcement": "none",
            "message": "Invalid license key",
            "gates_available": []
        }
    
    def generate_trial_license(self, email: str) -> Dict:
        """Generate a new trial license"""
        license_hash = hashlib.sha256(f"{email}{datetime.now().isoformat()}".encode()).hexdigest()
        license_key = f"ARF-TRIAL-{license_hash[:8].upper()}"
        
        self.active_licenses[license_key] = {
            "tier": "trial",
            "email": email,
            "expires": datetime.now() + timedelta(days=14),
            "created": datetime.now(),
            "features": self.license_tiers["trial"]["features"]
        }
        
        return {
            "success": True,
            "license_key": license_key,
            "tier": "trial",
            "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
            "features": self.license_tiers["trial"]["features"],
            "message": "14-day trial license generated successfully"
        }
    
    def get_tier_comparison(self) -> List[Dict]:
        """Get comparison of all license tiers"""
        comparison = []
        for tier_key, tier_info in self.license_tiers.items():
            comparison.append({
                "tier": tier_key,
                "name": tier_info["name"],
                "price": f"${tier_info['price']:,}/mo",
                "enforcement": tier_info["enforcement"].replace("_", " ").title(),
                "max_agents": tier_info["max_agents"],
                "gates": len(tier_info["gates_enabled"]),
                "features": tier_info["features"][:3]  # First 3 features
            })
        return comparison

class MockExecutionAuthorityService:
    """Simulates mechanical gate enforcement for Enterprise"""
    
    def __init__(self):
        self.gate_definitions = {
            "license_validation": {
                "description": "Validate enterprise license is active",
                "weight": 0.2,
                "required": True,
                "enterprise_only": True
            },
            "confidence_threshold": {
                "description": "Confidence score β‰₯ 0.70",
                "weight": 0.25,
                "required": True,
                "threshold": 0.7
            },
            "risk_assessment": {
                "description": "Risk score ≀ 0.80",
                "weight": 0.25,
                "required": True,
                "threshold": 0.8
            },
            "rollback_feasibility": {
                "description": "Rollback plan exists and is feasible",
                "weight": 0.1,
                "required": False,
                "enterprise_only": False
            },
            "admin_approval": {
                "description": "Human approval for sensitive actions",
                "weight": 0.1,
                "required": False,
                "enterprise_only": True
            },
            "compliance_check": {
                "description": "Compliance with regulations (GDPR, PCI, etc.)",
                "weight": 0.05,
                "required": False,
                "enterprise_only": True,
                "tiers": ["enterprise"]
            },
            "budget_check": {
                "description": "Within budget limits and forecasts",
                "weight": 0.05,
                "required": False,
                "enterprise_only": True
            }
        }
        
        self.audit_log = []
    
    def evaluate_gates(self, action_data: Dict, license_info: Dict) -> Dict:
        """Evaluate all mechanical gates for an action"""
        gate_results = {}
        required_gates = []
        optional_gates = []
        
        # Determine which gates to evaluate based on license
        license_tier = license_info.get("tier", "none")
        gates_available = license_info.get("gates_available", [])
        
        for gate_name, gate_def in self.gate_definitions.items():
            # Check if gate should be evaluated
            should_evaluate = (
                gate_name in gates_available or
                not gate_def.get("enterprise_only", False)
            )
            
            if should_evaluate:
                if gate_def["required"]:
                    required_gates.append(gate_name)
                else:
                    optional_gates.append(gate_name)
                
                # Evaluate the gate
                gate_results[gate_name] = self._evaluate_single_gate(
                    gate_name, gate_def, action_data, license_tier
                )
        
        # Calculate overall status
        passed_gates = sum(1 for r in gate_results.values() if r["passed"])
        total_gates = len(gate_results)
        
        # Check if all required gates passed
        all_required_passed = all(
            gate_results[gate]["passed"] 
            for gate in required_gates 
            if gate in gate_results
        )
        
        # Determine execution authority
        if not license_info.get("valid", False):
            execution_authority = "OSS_ONLY"
        elif license_tier == "trial":
            execution_authority = "ADVISORY_ONLY"
        elif all_required_passed:
            if license_tier in ["professional", "enterprise"]:
                execution_authority = "AUTONOMOUS_EXECUTION"
            else:
                execution_authority = "HUMAN_APPROVAL_REQUIRED"
        else:
            execution_authority = "BLOCKED"
        
        # Log to audit trail
        audit_entry = self._log_to_audit(action_data, gate_results, execution_authority, license_tier)
        
        return {
            "gate_results": gate_results,
            "required_gates": required_gates,
            "optional_gates": optional_gates,
            "passed_gates": passed_gates,
            "total_gates": total_gates,
            "all_required_passed": all_required_passed,
            "execution_authority": execution_authority,
            "audit_id": audit_entry["audit_id"],
            "recommendation": self._generate_recommendation(execution_authority, passed_gates, total_gates)
        }
    
    def _evaluate_single_gate(self, gate_name: str, gate_def: Dict, 
                             action_data: Dict, license_tier: str) -> Dict:
        """Evaluate a single gate"""
        confidence = action_data.get("confidence", 0.5)
        risk_score = action_data.get("risk_score", 0.5)
        action = action_data.get("action", "")
        
        gate_result = {
            "gate_name": gate_name,
            "description": gate_def["description"],
            "weight": gate_def["weight"],
            "required": gate_def["required"]
        }
        
        # Gate-specific evaluation logic
        if gate_name == "license_validation":
            passed = license_tier != "none"
            message = f"License valid: {license_tier}" if passed else "No valid license"
        
        elif gate_name == "confidence_threshold":
            threshold = gate_def.get("threshold", 0.7)
            passed = confidence >= threshold
            message = f"Confidence {confidence:.2f} β‰₯ {threshold}" if passed else f"Confidence {confidence:.2f} < {threshold}"
        
        elif gate_name == "risk_assessment":
            threshold = gate_def.get("threshold", 0.8)
            passed = risk_score <= threshold
            message = f"Risk {risk_score:.2f} ≀ {threshold}" if passed else f"Risk {risk_score:.2f} > {threshold}"
        
        elif gate_name == "rollback_feasibility":
            # Check if action has rollback
            has_rollback = not any(word in action.lower() for word in ["drop", "delete", "truncate", "rm -rf"])
            passed = has_rollback
            message = "Rollback feasible" if has_rollback else "No rollback possible"
        
        elif gate_name == "admin_approval":
            # For demo, always pass if not high risk
            passed = risk_score < 0.7
            message = "Admin approval not required" if passed else "Admin approval needed"
        
        elif gate_name == "compliance_check":
            # Check for sensitive data access
            sensitive_keywords = ["pci", "credit card", "ssn", "password", "token"]
            has_sensitive = any(keyword in action.lower() for keyword in sensitive_keywords)
            passed = not has_sensitive or license_tier == "enterprise"
            message = "Compliant" if passed else "Requires Enterprise for sensitive data"
        
        elif gate_name == "budget_check":
            # Mock budget check
            passed = True
            message = "Within budget limits"
        
        else:
            passed = True
            message = "Gate evaluation passed"
        
        gate_result.update({
            "passed": passed,
            "message": message,
            "details": {
                "confidence": confidence,
                "risk_score": risk_score,
                "action_type": self._categorize_action(action)
            }
        })
        
        return gate_result
    
    def _categorize_action(self, action: str) -> str:
        """Categorize the action type"""
        action_lower = action.lower()
        
        if any(word in action_lower for word in ["drop", "delete", "truncate"]):
            return "destructive"
        elif any(word in action_lower for word in ["deploy", "release", "update"]):
            return "deployment"
        elif any(word in action_lower for word in ["select", "read", "get", "fetch"]):
            return "read"
        elif any(word in action_lower for word in ["insert", "update", "modify"]):
            return "write"
        elif any(word in action_lower for word in ["grant", "revoke", "permission"]):
            return "access_control"
        else:
            return "other"
    
    def _log_to_audit(self, action_data: Dict, gate_results: Dict, 
                     authority: str, license_tier: str) -> Dict:
        """Log to audit trail"""
        audit_id = str(uuid.uuid4())[:8]
        
        entry = {
            "audit_id": audit_id,
            "timestamp": datetime.now().isoformat(),
            "action": action_data.get("action", ""),
            "license_tier": license_tier,
            "execution_authority": authority,
            "gate_summary": {
                "passed": sum(1 for r in gate_results.values() if r["passed"]),
                "total": len(gate_results)
            },
            "risk_score": action_data.get("risk_score", 0),
            "confidence": action_data.get("confidence", 0)
        }
        
        self.audit_log.append(entry)
        
        # Keep only last 1000 entries
        if len(self.audit_log) > 1000:
            self.audit_log = self.audit_log[-1000:]
        
        return entry
    
    def _generate_recommendation(self, authority: str, passed: int, total: int) -> str:
        """Generate recommendation based on gate results"""
        if authority == "AUTONOMOUS_EXECUTION":
            return f"βœ… Safe for autonomous execution ({passed}/{total} gates passed)"
        elif authority == "HUMAN_APPROVAL_REQUIRED":
            return f"πŸ‘€ Requires human approval ({passed}/{total} gates passed)"
        elif authority == "BLOCKED":
            return f"🚫 Blocked by mechanical gates ({passed}/{total} gates passed)"
        elif authority == "ADVISORY_ONLY":
            return f"ℹ️  Trial license - advisory only ({passed}/{total} gates would pass)"
        else:
            return f"πŸ”΅ OSS mode - advisory only"

# Demo Configuration
class DemoConfig:
    """Configuration for the demo"""
    
    OSS_THEME = {
        "primary": "#1E88E5",  # Blue
        "secondary": "#64B5F6",
        "background": "#E3F2FD",
        "text": "#1565C0",
        "border": "#90CAF9"
    }
    
    ENTERPRISE_THEME = {
        "primary": "#FFB300",  # Gold
        "secondary": "#FFD54F",
        "background": "#FFF8E1",
        "text": "#FF8F00",
        "border": "#FFE082"
    }
    
    RISK_COLORS = {
        "low": "#4CAF50",     # Green
        "medium": "#FF9800",   # Orange
        "high": "#F44336",     # Red
        "critical": "#D32F2F"  # Dark red
    }
    
    @staticmethod
    def get_risk_level(score: float) -> Tuple[str, str]:
        """Get risk level and color from score"""
        if score < 0.3:
            return "low", DemoConfig.RISK_COLORS["low"]
        elif score < 0.6:
            return "medium", DemoConfig.RISK_COLORS["medium"]
        elif score < 0.8:
            return "high", DemoConfig.RISK_COLORS["high"]
        else:
            return "critical", DemoConfig.RISK_COLORS["critical"]

# Load demo scenarios
try:
    from demo_scenarios import DEMO_SCENARIOS, LICENSE_TIERS, VALUE_PROPOSITIONS
    print("βœ… Demo scenarios loaded successfully")
except ImportError:
    print("⚠️  Demo scenarios not found, using built-in scenarios")
    
    DEMO_SCENARIOS = {
        "database_drop": {
            "name": "High-Risk Database Operation",
            "action": "DROP DATABASE production CASCADE",
            "description": "Irreversible deletion of production database",
            "context": {"environment": "production", "criticality": "critical"}
        },
        "service_deployment": {
            "name": "Safe Service Deployment",
            "action": "deploy_service v1.2.3 to staging with 25% canary",
            "description": "Standard deployment with canary testing",
            "context": {"environment": "staging", "canary": 25}
        },
        "config_change": {
            "name": "Configuration Change",
            "action": "UPDATE config SET timeout=30 WHERE service='payment'",
            "description": "Update payment service timeout configuration",
            "context": {"environment": "production", "service": "payment"}
        }
    }

# Main ARF Processor
class ARFProcessor:
    """Main processor for ARF operations"""
    
    def __init__(self):
        self.policy_engine = PolicyEngine()
        self.reliability_engine = ReliabilityEngine()
        self.license_manager = MockEnterpriseLicenseManager()
        self.execution_service = MockExecutionAuthorityService()
        self.processed_actions = []
        
        print(f"βœ… ARF Processor initialized with {ARF_VERSION}")
    
    def process_oss(self, action: str, context: Dict = None) -> Dict:
        """Process action through ARF OSS"""
        start_time = time.time()
        
        # Create reliability event
        event = ReliabilityEvent(
            event_id=str(uuid.uuid4())[:8],
            agent_id="demo_agent",
            action=action,
            timestamp=datetime.now(),
            context=context or {}
        )
        
        # Calculate reliability score
        reliability_result = self.reliability_engine.calculate_score(event)
        
        # Evaluate policies
        if hasattr(self.policy_engine, 'evaluate'):
            # Mock policy engine
            violations = self.policy_engine.evaluate(event, reliability_result['overall'])
        else:
            # Real ARF policy engine
            violations = []
            # Note: Real implementation would call actual policy evaluation
        
        # Determine recommendation
        risk_level, risk_color = DemoConfig.get_risk_level(reliability_result['risk_score'])
        
        if violations:
            can_execute = False
            recommendation = f"❌ Blocked by {len(violations)} policy violation(s)"
        else:
            if reliability_result['overall'] >= 0.8:
                can_execute = True
                recommendation = "βœ… Safe to execute"
            elif reliability_result['overall'] >= 0.6:
                can_execute = False
                recommendation = "⚠️ Review recommended"
            else:
                can_execute = False
                recommendation = "🚫 High risk - do not execute"
        
        processing_time = time.time() - start_time
        
        result = {
            "action": action,
            "reliability_score": reliability_result['overall'],
            "confidence": reliability_result['confidence'],
            "risk_score": reliability_result['risk_score'],
            "risk_level": risk_level,
            "risk_color": risk_color,
            "policy_violations": len(violations),
            "violation_details": violations[:3] if violations else [],
            "recommendation": recommendation,
            "can_execute": can_execute,
            "processing_time": round(processing_time, 3),
            "engine_version": ARF_VERSION,
            "mode": "OSS",
            "limitation": "Advisory only - human must make final decision"
        }
        
        # Store for history
        self.processed_actions.append({
            "timestamp": datetime.now(),
            "result": result,
            "mode": "OSS"
        })
        
        return result
    
    def process_enterprise(self, action: str, license_key: str, context: Dict = None) -> Dict:
        """Process action through ARF Enterprise"""
        # First get OSS result
        oss_result = self.process_oss(action, context)
        
        # Validate license
        license_info = self.license_manager.validate_license(license_key)
        
        # Prepare action data for gate evaluation
        action_data = {
            "action": action,
            "confidence": oss_result["confidence"],
            "risk_score": oss_result["risk_score"],
            "reliability": oss_result["reliability_score"],
            "context": context or {}
        }
        
        # Evaluate mechanical gates
        gate_evaluation = self.execution_service.evaluate_gates(action_data, license_info)
        
        # Combine results
        enterprise_result = {
            **oss_result,
            "license_info": license_info,
            "gate_evaluation": gate_evaluation,
            "mode": "Enterprise",
            "engine_version": f"{ARF_VERSION} Enterprise",
            "benefit": "Mechanical enforcement with automated decision making"
        }
        
        # Store for history
        self.processed_actions.append({
            "timestamp": datetime.now(),
            "result": enterprise_result,
            "mode": "Enterprise",
            "license_tier": license_info.get("tier", "none")
        })
        
        return enterprise_result
    
    def get_stats(self) -> Dict:
        """Get processing statistics"""
        total = len(self.processed_actions)
        oss_count = sum(1 for a in self.processed_actions if a["mode"] == "OSS")
        enterprise_count = total - oss_count
        
        if total == 0:
            return {"total": 0}
        
        # Calculate average scores
        avg_reliability = np.mean([a["result"]["reliability_score"] for a in self.processed_actions])
        avg_risk = np.mean([a["result"]["risk_score"] for a in self.processed_actions])
        
        # Count executions
        executed = sum(1 for a in self.processed_actions if a["result"].get("can_execute", False))
        
        return {
            "total_processed": total,
            "oss_actions": oss_count,
            "enterprise_actions": enterprise_count,
            "avg_reliability": round(avg_reliability, 3),
            "avg_risk": round(avg_risk, 3),
            "execution_rate": round(executed / total * 100, 1) if total > 0 else 0
        }

# Create global processor instance
arf_processor = ARFProcessor()

# Gradio Interface Components
def create_oss_panel_html(result: Dict) -> str:
    """Generate HTML for OSS results panel"""
    risk_color = result.get("risk_color", "#666666")
    
    # Policy violations display
    violations_html = ""
    if result.get("policy_violations", 0) > 0:
        violations = result.get("violation_details", [])
        violations_html = """
        <div style="background: #FFEBEE; padding: 10px; border-radius: 6px; margin: 10px 0; border-left: 4px solid #F44336;">
            <div style="font-weight: 500; color: #D32F2F; margin-bottom: 5px;">
                ⚠️ Policy Violations Detected
            </div>
        """
        for i, violation in enumerate(violations[:3]):
            if isinstance(violation, dict):
                reason = violation.get('reason', 'Policy violation')
            else:
                reason = str(violation)
            violations_html += f"""
            <div style="font-size: 12px; color: #666; margin: 2px 0;">
                β€’ {reason[:80]}{'...' if len(reason) > 80 else ''}
            </div>
            """
        violations_html += "</div>"
    
    return f"""
    <div style="border: 2px solid {DemoConfig.OSS_THEME['border']}; border-radius: 12px; overflow: hidden; margin-bottom: 20px;">
        <div style="background: {DemoConfig.OSS_THEME['primary']}; color: white; padding: 15px;">
            <div style="display: flex; align-items: center;">
                <span style="font-size: 24px; margin-right: 10px;">πŸ”΅</span>
                <div>
                    <h3 style="margin: 0; font-size: 18px;">ARF {result.get('engine_version', '3.3.9')} OSS</h3>
                    <div style="font-size: 12px; opacity: 0.9;">Open Source Edition</div>
                </div>
            </div>
        </div>
        
        <div style="padding: 20px; background: white;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="text-align: center; padding: 15px; background: {DemoConfig.OSS_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {DemoConfig.OSS_THEME['text']}; margin-bottom: 5px;">Reliability Score</div>
                    <div style="font-size: 24px; font-weight: bold; color: {DemoConfig.OSS_THEME['primary']};">
                        {result['reliability_score']:.1%}
                    </div>
                </div>
                
                <div style="text-align: center; padding: 15px; background: {DemoConfig.OSS_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {risk_color}; margin-bottom: 5px;">Risk Level</div>
                    <div style="font-size: 24px; font-weight: bold; color: {risk_color};">
                        {result['risk_level'].upper()}
                    </div>
                </div>
                
                <div style="text-align: center; padding: 15px; background: {DemoConfig.OSS_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {DemoConfig.OSS_THEME['text']}; margin-bottom: 5px;">Confidence</div>
                    <div style="font-size: 24px; font-weight: bold; color: {DemoConfig.OSS_THEME['primary']};">
                        {result['confidence']:.1%}
                    </div>
                </div>
            </div>
            
            <div style="background: #F5F5F5; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid {risk_color};">
                <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <span style="font-size: 24px; margin-right: 10px;">πŸ’‘</span>
                    <h4 style="margin: 0; color: #333;">Recommendation</h4>
                </div>
                <p style="margin: 0; font-size: 16px; color: #333; font-weight: 500;">
                    {result['recommendation']}
                </p>
                <p style="margin: 5px 0 0 0; font-size: 12px; color: #666;">
                    Processing time: {result['processing_time']}s
                </p>
            </div>
            
            {violations_html}
            
            <div style="background: #FFF3E0; padding: 15px; border-radius: 8px; margin-top: 15px;">
                <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <span style="font-size: 24px; margin-right: 10px;">⚠️</span>
                    <h4 style="margin: 0; color: #E65100;">OSS Limitations</h4>
                </div>
                <p style="margin: 0; color: #E65100;">
                    <strong>Advisory Only:</strong> {result['limitation']}
                </p>
                <p style="margin: 5px 0; color: #E65100;">
                    <strong>Execution Authority:</strong> {'βœ… Can execute (advisory)' if result['can_execute'] else '❌ Cannot execute - human decision required'}
                </p>
            </div>
        </div>
    </div>
    """

def create_enterprise_panel_html(result: Dict) -> str:
    """Generate HTML for Enterprise results panel"""
    license_info = result.get("license_info", {})
    gate_eval = result.get("gate_evaluation", {})
    gate_results = gate_eval.get("gate_results", {})
    
    license_tier = license_info.get("tier", "none")
    tier_name = license_info.get("name", "No License").title()
    
    # Determine panel color based on tier
    if license_tier == "enterprise":
        tier_color = "#FF6F00"  # Darker orange
    elif license_tier == "professional":
        tier_color = "#FFB300"  # Gold
    elif license_tier == "starter":
        tier_color = "#FFD54F"  # Light gold
    elif license_tier == "trial":
        tier_color = "#BCAAA4"  # Grayish
    else:
        tier_color = "#9E9E9E"  # Gray
    
    # Generate gates HTML
    gates_html = ""
    for gate_name, gate_result in gate_results.items():
        gate_passed = gate_result.get("passed", False)
        gate_color = "#4CAF50" if gate_passed else "#F44336"
        gate_required = gate_result.get("required", False)
        
        gates_html += f"""
        <div style="display: flex; align-items: center; padding: 8px 12px; margin: 5px 0; 
                    background: {'#E8F5E9' if gate_passed else '#FFEBEE'}; 
                    border-radius: 6px; border-left: 4px solid {gate_color};">
            <span style="margin-right: 10px; font-size: 18px; color: {gate_color};">
                {'βœ…' if gate_passed else '❌'}
            </span>
            <div style="flex: 1;">
                <div style="display: flex; justify-content: space-between;">
                    <div style="font-weight: 500; font-size: 14px;">
                        {gate_name.replace('_', ' ').title()}
                        {'' if gate_required else ' (Optional)'}
                    </div>
                    <div style="font-size: 12px; color: #666; font-weight: 500;">
                        {gate_result.get('weight', 0):.0%}
                    </div>
                </div>
                <div style="font-size: 12px; color: #666; margin-top: 2px;">
                    {gate_result.get('message', '')}
                </div>
            </div>
        </div>
        """
    
    if not gates_html:
        gates_html = """
        <div style="text-align: center; padding: 20px; color: #666;">
            <div style="font-size: 48px; margin-bottom: 10px;">πŸ”’</div>
            <div>Enterprise gates require a valid license</div>
            <div style="font-size: 12px; margin-top: 5px;">Get a trial license to see gate evaluation</div>
        </div>
        """
    
    # Execution authority display
    authority = gate_eval.get("execution_authority", "OSS_ONLY")
    authority_display = authority.replace("_", " ").title()
    
    if authority == "AUTONOMOUS_EXECUTION":
        authority_color = "#4CAF50"
        authority_icon = "βœ…"
        authority_message = "Autonomous execution permitted"
    elif authority == "HUMAN_APPROVAL_REQUIRED":
        authority_color = "#FF9800"
        authority_icon = "πŸ‘€"
        authority_message = "Human approval required"
    elif authority == "BLOCKED":
        authority_color = "#F44336"
        authority_icon = "🚫"
        authority_message = "Blocked by mechanical gates"
    elif authority == "ADVISORY_ONLY":
        authority_color = "#9E9E9E"
        authority_icon = "ℹ️"
        authority_message = "Trial license - advisory only"
    else:
        authority_color = "#2196F3"
        authority_icon = "πŸ”΅"
        authority_message = "OSS mode - no license"
    
    passed_gates = gate_eval.get("passed_gates", 0)
    total_gates = gate_eval.get("total_gates", 0)
    
    return f"""
    <div style="border: 2px solid {tier_color}; border-radius: 12px; overflow: hidden; margin-bottom: 20px;">
        <div style="background: linear-gradient(135deg, {tier_color} 0%, {DemoConfig.ENTERPRISE_THEME['secondary']} 100%); 
                    color: white; padding: 15px;">
            <div style="display: flex; align-items: center; justify-content: space-between;">
                <div style="display: flex; align-items: center;">
                    <span style="font-size: 24px; margin-right: 10px;">🟑</span>
                    <div>
                        <h3 style="margin: 0; font-size: 18px;">ARF {result.get('engine_version', '3.3.9')}</h3>
                        <div style="font-size: 12px; opacity: 0.9;">{tier_name} Edition</div>
                    </div>
                </div>
                <div style="background: rgba(255, 255, 255, 0.2); padding: 4px 12px; border-radius: 20px; font-size: 12px;">
                    {license_info.get('enforcement', 'advisory').replace('_', ' ').title()}
                </div>
            </div>
        </div>
        
        <div style="padding: 20px; background: white;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="text-align: center; padding: 15px; background: {DemoConfig.ENTERPRISE_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {DemoConfig.ENTERPRISE_THEME['text']}; margin-bottom: 5px;">License Tier</div>
                    <div style="font-size: 20px; font-weight: bold; color: {DemoConfig.ENTERPRISE_THEME['primary']};">
                        {tier_name}
                    </div>
                </div>
                
                <div style="text-align: center; padding: 15px; background: {DemoConfig.ENTERPRISE_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {DemoConfig.ENTERPRISE_THEME['text']}; margin-bottom: 5px;">Gates Passed</div>
                    <div style="font-size: 24px; font-weight: bold; color: {DemoConfig.ENTERPRISE_THEME['primary']};">
                        {passed_gates}/{total_gates}
                    </div>
                </div>
                
                <div style="text-align: center; padding: 15px; background: {DemoConfig.ENTERPRISE_THEME['background']}; border-radius: 8px;">
                    <div style="font-size: 12px; color: {DemoConfig.ENTERPRISE_THEME['text']}; margin-bottom: 5px;">Enforcement</div>
                    <div style="font-size: 14px; font-weight: bold; color: {DemoConfig.ENTERPRISE_THEME['primary']}; line-height: 1.2;">
                        {license_info.get('enforcement', 'advisory').replace('_', ' ').title()}
                    </div>
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <h4 style="margin-bottom: 10px; color: {DemoConfig.ENTERPRISE_THEME['text']};">Mechanical Gates</h4>
                <div style="max-height: 300px; overflow-y: auto; padding-right: 5px;">
                    {gates_html}
                </div>
            </div>
            
            <div style="background: {authority_color}20; padding: 20px; border-radius: 8px; 
                        text-align: center; border: 2px solid {authority_color}; margin-bottom: 20px;">
                <div style="font-size: 48px; margin-bottom: 10px;">{authority_icon}</div>
                <div style="font-size: 24px; font-weight: bold; color: {authority_color}; margin-bottom: 5px;">
                    {authority_display}
                </div>
                <div style="color: {authority_color}; font-size: 14px;">
                    {authority_message}
                </div>
                <div style="font-size: 12px; color: #666; margin-top: 10px;">
                    {gate_eval.get('recommendation', '')}
                </div>
            </div>
            
            <div style="background: #E8F5E9; padding: 15px; border-radius: 8px;">
                <div style="display: flex; align-items: center; margin-bottom: 10px;">
                    <span style="font-size: 24px; margin-right: 10px;">πŸš€</span>
                    <h4 style="margin: 0; color: #2E7D32;">Enterprise Benefits</h4>
                </div>
                <p style="margin: 0; color: #2E7D32;">
                    <strong>Mechanical Enforcement:</strong> {result.get('benefit', 'Automated decision making')}
                </p>
                <p style="margin: 5px 0; color: #2E7D32;">
                    <strong>Audit Trail:</strong> ID: {gate_eval.get('audit_id', 'Available with license')}
                </p>
                <p style="margin: 0; color: #2E7D32;">
                    <strong>Decision Speed:</strong> {result.get('processing_time', 0):.3f}s
                </p>
            </div>
        </div>
    </div>
    """

def create_comparison_html(oss_result: Dict, enterprise_result: Dict) -> str:
    """Create comparison visualization"""
    oss_can_execute = oss_result.get('can_execute', False)
    enterprise_authority = enterprise_result.get('gate_evaluation', {}).get('execution_authority', 'OSS_ONLY')
    
    # Calculate improvements
    risk_reduction = 0.92  # 92% risk reduction
    speed_improvement = 100  # 100x faster
    false_positive_reduction = 0.85  # 85% reduction
    cost_reduction = 0.75  # 75% OpEx reduction
    
    # Determine enterprise value
    if enterprise_authority == "AUTONOMOUS_EXECUTION":
        value_score = 95
        value_message = "Full autonomous execution enabled"
    elif enterprise_authority == "HUMAN_APPROVAL_REQUIRED":
        value_score = 70
        value_message = "Human oversight with mechanical validation"
    elif enterprise_authority == "BLOCKED":
        value_score = 90  # Still valuable because it prevented a bad action
        value_message = "Risk prevented by mechanical gates"
    else:
        value_score = 30
        value_message = "Upgrade needed for mechanical enforcement"
    
    return f"""
    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px;">
        <h3 style="margin-top: 0; text-align: center; color: #333;">πŸ“Š Side-by-Side Comparison</h3>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 30px;">
            <!-- OSS Column -->
            <div style="text-align: center;">
                <div style="background: {DemoConfig.OSS_THEME['background']}; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h4 style="color: {DemoConfig.OSS_THEME['primary']}; margin: 0 0 10px 0;">πŸ”΅ OSS 3.3.9</h4>
                    <div style="font-size: 48px; color: {DemoConfig.OSS_THEME['primary']}; margin-bottom: 10px;">
                        {'⚠️' if not oss_can_execute else 'βœ…'}
                    </div>
                    <div style="font-size: 18px; font-weight: bold; color: {'#E53935' if not oss_can_execute else '#43A047'};">
                        {'Advisory Only' if not oss_can_execute else 'Can Execute'}
                    </div>
                </div>
                <div style="text-align: left;">
                    <div style="background: #E3F2FD; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        <strong>Human Decision Required</strong>
                    </div>
                    <div style="background: #E3F2FD; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        Risk: {oss_result.get('risk_level', 'Unknown').upper()}
                    </div>
                    <div style="background: #E3F2FD; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        {oss_result.get('policy_violations', 0)} Policy Violations
                    </div>
                    <div style="background: #E3F2FD; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        Processing: {oss_result.get('processing_time', 0):.3f}s
                    </div>
                </div>
            </div>
            
            <!-- Enterprise Column -->
            <div style="text-align: center;">
                <div style="background: {DemoConfig.ENTERPRISE_THEME['background']}; padding: 15px; border-radius: 10px; margin-bottom: 15px;">
                    <h4 style="color: {DemoConfig.ENTERPRISE_THEME['primary']}; margin: 0 0 10px 0;">
                        🟑 Enterprise
                    </h4>
                    <div style="font-size: 48px; color: {DemoConfig.ENTERPRISE_THEME['primary']}; margin-bottom: 10px;">
                        {'βœ…' if enterprise_authority == 'AUTONOMOUS_EXECUTION' else 'β›”' if enterprise_authority == 'BLOCKED' else 'πŸ‘€'}
                    </div>
                    <div style="font-size: 18px; font-weight: bold; color: {'#43A047' if enterprise_authority == 'AUTONOMOUS_EXECUTION' else '#F44336' if enterprise_authority == 'BLOCKED' else '#FF9800'};">
                        {enterprise_authority.replace('_', ' ').title()}
                    </div>
                </div>
                <div style="text-align: left;">
                    <div style="background: #FFF8E1; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        <strong>Mechanical Enforcement</strong>
                    </div>
                    <div style="background: #FFF8E1; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        {enterprise_result.get('gate_evaluation', {}).get('passed_gates', 0)}/{enterprise_result.get('gate_evaluation', {}).get('total_gates', 0)} Gates Passed
                    </div>
                    <div style="background: #FFF8E1; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        License: {enterprise_result.get('license_info', {}).get('name', 'Trial').title()}
                    </div>
                    <div style="background: #FFF8E1; padding: 8px 12px; border-radius: 6px; margin: 5px 0; font-size: 14px;">
                        Audit: {enterprise_result.get('gate_evaluation', {}).get('audit_id', 'N/A')[:8]}
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Value Proposition -->
        <div style="background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); 
                    padding: 20px; border-radius: 10px; margin-top: 20px;">
            <h4 style="text-align: center; margin-top: 0; color: #333;">🎯 Enterprise Value Proposition</h4>
            
            <div style="margin-bottom: 15px; text-align: center;">
                <div style="display: inline-block; background: white; padding: 10px 20px; 
                            border-radius: 20px; font-size: 18px; font-weight: bold; color: #FF8F00;">
                    Value Score: {value_score}/100
                </div>
                <div style="font-size: 14px; color: #666; margin-top: 5px;">
                    {value_message}
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;">
                <div style="text-align: center; padding: 10px; background: white; border-radius: 8px;">
                    <div style="font-size: 12px; color: #666; margin-bottom: 5px;">Risk Reduction</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">
                        {risk_reduction:.0%}
                    </div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 8px;">
                    <div style="font-size: 12px; color: #666; margin-bottom: 5px;">Decision Speed</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">
                        {speed_improvement}x
                    </div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 8px;">
                    <div style="font-size: 12px; color: #666; margin-bottom: 5px;">False Positives</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">
                        -{false_positive_reduction:.0%}
                    </div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 8px;">
                    <div style="font-size: 12px; color: #666; margin-bottom: 5px;">Operational Cost</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">
                        -{cost_reduction:.0%}
                    </div>
                </div>
            </div>
            
            <div style="text-align: center; font-size: 12px; color: #666; margin-top: 10px;">
                Based on industry benchmarks and customer data
            </div>
        </div>
        
        <!-- Upgrade CTA -->
        <div style="background: linear-gradient(135deg, #1E88E5 0%, #0D47A1 100%); 
                    color: white; padding: 20px; border-radius: 10px; margin-top: 20px; text-align: center;">
            <h3 style="margin: 0 0 10px 0; color: white;">πŸš€ Ready to Upgrade?</h3>
            <p style="margin: 0 0 15px 0; opacity: 0.9;">
                Get mechanical enforcement, audit trails, and autonomous execution
            </p>
            <div style="display: inline-flex; gap: 10px; flex-wrap: wrap; justify-content: center;">
                <div style="background: rgba(255, 255, 255, 0.2); padding: 8px 16px; border-radius: 20px;">
                    <strong>Starter:</strong> $2,000/mo
                </div>
                <div style="background: rgba(255, 255, 255, 0.2); padding: 8px 16px; border-radius: 20px;">
                    <strong>Professional:</strong> $5,000/mo
                </div>
                <div style="background: rgba(255, 255, 255, 0.2); padding: 8px 16px; border-radius: 20px;">
                    <strong>Enterprise:</strong> $15,000/mo
                </div>
            </div>
        </div>
    </div>
    """

def create_license_tier_html() -> str:
    """Create HTML for license tier comparison"""
    license_manager = MockEnterpriseLicenseManager()
    tiers = license_manager.get_tier_comparison()
    
    tiers_html = ""
    for tier in tiers:
        color = {
            "trial": "#BCAAA4",
            "starter": "#FFD54F",
            "professional": "#FFB300",
            "enterprise": "#FF6F00"
        }.get(tier["tier"], "#9E9E9E")
        
        features_html = ""
        for feature in tier["features"]:
            features_html += f'<li style="font-size: 12px; margin: 2px 0;">{feature}</li>'
        
        tiers_html += f"""
        <div style="border: 1px solid {color}; border-radius: 10px; overflow: hidden; margin: 10px 0;">
            <div style="background: {color}; color: white; padding: 12px; font-weight: bold;">
                {tier["name"]}
            </div>
            <div style="padding: 15px; background: white;">
                <div style="text-align: center; margin-bottom: 15px;">
                    <div style="font-size: 24px; font-weight: bold; color: #333;">
                        {tier["price"]}
                    </div>
                    <div style="font-size: 12px; color: #666;">
                        {tier["max_agents"]} agents β€’ {tier["gates"]} gates
                    </div>
                </div>
                <div style="margin-bottom: 15px;">
                    <div style="background: #F5F5F5; padding: 8px 12px; border-radius: 6px; font-size: 14px;">
                        <strong>Enforcement:</strong> {tier["enforcement"]}
                    </div>
                </div>
                <div>
                    <div style="font-size: 12px; font-weight: 500; color: #666; margin-bottom: 5px;">
                        Key Features:
                    </div>
                    <ul style="margin: 0; padding-left: 20px; color: #666;">
                        {features_html}
                    </ul>
                </div>
            </div>
        </div>
        """
    
    return f"""
    <div style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h3 style="margin-top: 0; color: #333; text-align: center;">πŸ’Ό License Tier Comparison</h3>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px;">
            {tiers_html}
        </div>
        <div style="text-align: center; margin-top: 20px; font-size: 12px; color: #666;">
            All plans include the full ARF 3.3.9 OSS engine plus mechanical gates
        </div>
    </div>
    """

# Gradio Interface
def create_demo_interface():
    """Create the main Gradio interface"""
    
    with gr.Blocks(
        title="Agentic Reliability Framework (ARF) 3.3.9 Demo",
        theme=gr.themes.Soft(
            primary_hue="blue",
            secondary_hue="orange",
            font=gr.themes.GoogleFont("Inter")
        ),
        css="""
        .gradio-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        .demo-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .action-history {
            max-height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 10px;
        }
        .stats-box {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 15px;
            border-radius: 10px;
            margin: 10px 0;
        }
        """
    ) as demo:
        
        # Header
        gr.Markdown("""
        <div class="demo-header">
            <h1 style="margin-bottom: 10px;">πŸ€– Agentic Reliability Framework (ARF) 3.3.9</h1>
            <h3 style="margin-top: 0; color: #666; font-weight: normal;">
                OSS Advisory vs Enterprise Mechanical Enforcement
            </h3>
            <p style="color: #666; max-width: 800px; margin: 0 auto 20px auto;">
                Experience the difference between open-source advisory recommendations 
                and enterprise mechanical enforcement with automated gate validation.
            </p>
        </div>
        """)
        
        # Stats bar
        stats = arf_processor.get_stats()
        gr.Markdown(f"""
        <div style="display: flex; justify-content: space-around; background: #F8F9FA; 
                    padding: 15px; border-radius: 10px; margin-bottom: 20px; flex-wrap: wrap;">
            <div style="text-align: center;">
                <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{stats['total_processed']}</div>
                <div style="font-size: 12px; color: #666;">Total Actions</div>
            </div>
            <div style="text-align: center;">
                <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{stats['oss_actions']}</div>
                <div style="font-size: 12px; color: #666;">OSS Evaluations</div>
            </div>
            <div style="text-align: center;">
                <div style="font-size: 24px; font-weight: bold; color: #FFB300;">{stats['enterprise_actions']}</div>
                <div style="font-size: 12px; color: #666;">Enterprise Evaluations</div>
            </div>
            <div style="text-align: center;">
                <div style="font-size: 24px; font-weight: bold; color: #4CAF50;">{stats['execution_rate']}%</div>
                <div style="font-size: 12px; color: #666;">Execution Rate</div>
            </div>
        </div>
        """)
        
        # Main control section
        with gr.Row():
            with gr.Column(scale=3):
                # Scenario selection
                scenario_select = gr.Dropdown(
                    choices=list(DEMO_SCENARIOS.keys()),
                    label="Select Demo Scenario",
                    value="database_drop",
                    elem_id="scenario_select"
                )
                
                # Action input
                action_input = gr.Textbox(
                    label="Action to Evaluate",
                    placeholder="Enter any action (e.g., DROP DATABASE production, deploy_service v1.2.3, etc.)",
                    value="DROP DATABASE production CASCADE",
                    lines=2,
                    elem_id="action_input"
                )
                
                # Context input
                context_input = gr.Textbox(
                    label="Context (JSON format)",
                    placeholder='{"environment": "production", "criticality": "high"}',
                    value='{"environment": "production"}',
                    lines=2,
                    elem_id="context_input"
                )
                
                # License input
                license_input = gr.Textbox(
                    label="Enterprise License Key (Optional)",
                    placeholder="Enter ARF-TRIAL-XXXXXXX or leave blank for OSS only",
                    value="",
                    elem_id="license_input"
                )
                
                # Process button
                with gr.Row():
                    process_btn = gr.Button(
                        "πŸš€ Process Action", 
                        variant="primary", 
                        size="lg",
                        elem_id="process_btn"
                    )
                    clear_btn = gr.Button(
                        "πŸ”„ Clear", 
                        variant="secondary",
                        elem_id="clear_btn"
                    )
            
            with gr.Column(scale=2):
                # Quick actions
                gr.Markdown("### Quick Actions")
                quick_actions = gr.Radio(
                    choices=["High Risk", "Medium Risk", "Low Risk", "Custom"],
                    label="Pre-built Examples",
                    value="High Risk",
                    elem_id="quick_actions"
                )
                
                # License status
                license_status = gr.HTML(
                    value="<div style='text-align: center; padding: 15px; background: #F5F5F5; border-radius: 8px;'>"
                          "<div style='font-size: 14px; color: #666;'>No license entered</div>"
                          "<div style='font-size: 12px; color: #999;'>Using OSS mode</div>"
                          "</div>",
                    label="License Status"
                )
                
                # Stats display
                gr.Markdown("### πŸ“ˆ Live Statistics")
                stats_display = gr.HTML(elem_id="stats_display")
        
        # Results section
        with gr.Row():
            with gr.Column(scale=1):
                oss_results_html = gr.HTML(
                    label="ARF OSS Results",
                    elem_id="oss_results"
                )
            
            with gr.Column(scale=1):
                enterprise_results_html = gr.HTML(
                    label="ARF Enterprise Results",
                    elem_id="enterprise_results"
                )
        
        # Comparison section
        comparison_html = gr.HTML(
            label="Side-by-Side Comparison",
            elem_id="comparison_html"
        )
        
        # License tier section
        license_tier_html = gr.HTML(
            value=create_license_tier_html(),
            label="License Tiers",
            elem_id="license_tier_html"
        )
        
        # Trial license section
        with gr.Accordion("🎁 Get 14-Day Trial License", open=False):
            with gr.Row():
                with gr.Column(scale=2):
                    trial_email = gr.Textbox(
                        label="Work Email",
                        placeholder="you@company.com",
                        elem_id="trial_email"
                    )
                    trial_btn = gr.Button(
                        "Get Trial License", 
                        variant="primary",
                        elem_id="trial_btn"
                    )
                
                with gr.Column(scale=3):
                    trial_output = gr.JSON(
                        label="Your Trial License",
                        elem_id="trial_output"
                    )
        
        # Footer
        gr.Markdown("""
        <div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; color: #666;">
            <p>
                <strong>ARF 3.3.9 Demo</strong> | 
                <a href="https://arf.dev" target="_blank">Website</a> | 
                <a href="https://github.com/arf-dev" target="_blank">GitHub</a> | 
                <a href="mailto:sales@arf.dev">Contact Sales</a>
            </p>
            <p style="font-size: 12px;">
                This demo uses real ARF 3.3.9 OSS code with simulated Enterprise features for demonstration purposes.<br>
                Actual Enterprise features may vary. Mechanical gates shown are simulated for demo purposes.
            </p>
        </div>
        """)
        
        # Function to process action
        def process_action(scenario, action, context_str, license_key, quick_action):
            """Process an action through both OSS and Enterprise"""
            try:
                # Update action based on quick action selection
                if quick_action != "Custom":
                    if quick_action == "High Risk":
                        action = "DELETE FROM users WHERE created_at < '2023-01-01'"
                    elif quick_action == "Medium Risk":
                        action = "ALTER TABLE payments ADD COLUMN processed_at TIMESTAMP"
                    elif quick_action == "Low Risk":
                        action = "SELECT COUNT(*) FROM logs WHERE level = 'ERROR'"
                
                # Parse context
                try:
                    context = json.loads(context_str) if context_str.strip() else {}
                except:
                    context = {"environment": "production"}
                
                # Use scenario if provided
                if scenario and scenario in DEMO_SCENARIOS:
                    scenario_data = DEMO_SCENARIOS[scenario]
                    action = scenario_data["action"]
                    context = {**context, **scenario_data.get("context", {})}
                
                # Process through OSS
                oss_result = arf_processor.process_oss(action, context)
                
                # Process through Enterprise
                enterprise_result = arf_processor.process_enterprise(action, license_key, context)
                
                # Create HTML displays
                oss_html = create_oss_panel_html(oss_result)
                enterprise_html = create_enterprise_panel_html(enterprise_result)
                comparison = create_comparison_html(oss_result, enterprise_result)
                
                # Update stats
                stats = arf_processor.get_stats()
                stats_display_html = f"""
                <div style="background: #F8F9FA; padding: 15px; border-radius: 10px;">
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                        <div>
                            <div style="font-size: 12px; color: #666;">Avg Reliability</div>
                            <div style="font-size: 18px; font-weight: bold; color: #1E88E5;">
                                {stats['avg_reliability']:.1%}
                            </div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #666;">Avg Risk</div>
                            <div style="font-size: 18px; font-weight: bold; color: #F44336;">
                                {stats['avg_risk']:.1%}
                            </div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #666;">OSS Actions</div>
                            <div style="font-size: 18px; font-weight: bold; color: #1E88E5;">
                                {stats['oss_actions']}
                            </div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #666;">Enterprise Actions</div>
                            <div style="font-size: 18px; font-weight: bold; color: #FFB300;">
                                {stats['enterprise_actions']}
                            </div>
                        </div>
                    </div>
                </div>
                """
                
                # Update license status
                license_info = enterprise_result.get("license_info", {})
                if license_info.get("valid", False):
                    license_status_html = f"""
                    <div style="text-align: center; padding: 15px; background: #E8F5E9; border-radius: 8px;">
                        <div style="font-size: 14px; color: #2E7D32; font-weight: 500;">
                            βœ… {license_info.get('name', 'License').title()} Active
                        </div>
                        <div style="font-size: 12px; color: #666;">
                            Expires: {license_info.get('expires', 'N/A')} β€’ {len(license_info.get('gates_available', []))} gates enabled
                        </div>
                    </div>
                    """
                else:
                    license_status_html = """
                    <div style="text-align: center; padding: 15px; background: #F5F5F5; border-radius: 8px;">
                        <div style="font-size: 14px; color: #666;">No license entered</div>
                        <div style="font-size: 12px; color: #999;">Using OSS mode</div>
                    </div>
                    """
                
                return (
                    oss_html, 
                    enterprise_html, 
                    comparison, 
                    stats_display_html,
                    license_status_html,
                    oss_result,  # For debugging
                    enterprise_result  # For debugging
                )
                
            except Exception as e:
                error_html = f"""
                <div style="background: #FFEBEE; padding: 20px; border-radius: 10px; color: #D32F2F;">
                    <h4 style="margin-top: 0;">❌ Error Processing Action</h4>
                    <p>{str(e)}</p>
                    <pre style="font-size: 12px; background: rgba(0,0,0,0.05); padding: 10px; border-radius: 5px; overflow: auto;">
{traceback.format_exc()}
                    </pre>
                </div>
                """
                return error_html, error_html, error_html, "", "", {}, {}
        
        # Function to generate trial license
        def generate_trial_license(email: str):
            """Generate a trial license"""
            if not email or "@" not in email:
                return {
                    "error": "Please enter a valid email address",
                    "success": False
                }
            
            try:
                license_manager = MockEnterpriseLicenseManager()
                result = license_manager.generate_trial_license(email)
                
                # Also update the global processor's license manager
                arf_processor.license_manager = license_manager
                
                return result
            except Exception as e:
                return {
                    "error": str(e),
                    "success": False
                }
        
        # Function to clear inputs
        def clear_inputs():
            return "", "", "", "High Risk", "", "", "", "", {}
        
        # Function to update quick action
        def update_quick_action(quick_action):
            examples = {
                "High Risk": '{"environment": "production", "criticality": "high"}',
                "Medium Risk": '{"environment": "staging", "service": "api"}',
                "Low Risk": '{"environment": "development", "read_only": true}',
                "Custom": '{}'
            }
            
            actions = {
                "High Risk": "DELETE FROM users WHERE created_at < '2023-01-01'",
                "Medium Risk": "ALTER TABLE payments ADD COLUMN processed_at TIMESTAMP",
                "Low Risk": "SELECT COUNT(*) FROM logs WHERE level = 'ERROR'",
                "Custom": ""
            }
            
            return actions[quick_action], examples[quick_action]
        
        # Function to update scenario
        def update_scenario(scenario):
            if scenario in DEMO_SCENARIOS:
                data = DEMO_SCENARIOS[scenario]
                action = data["action"]
                context = json.dumps(data.get("context", {}), indent=2)
                return action, context
            return "", "{}"
        
        # Connect events
        process_btn.click(
            fn=process_action,
            inputs=[scenario_select, action_input, context_input, license_input, quick_actions],
            outputs=[oss_results_html, enterprise_results_html, comparison_html, 
                    stats_display, license_status, gr.JSON(visible=False), gr.JSON(visible=False)],
            queue=True
        )
        
        clear_btn.click(
            fn=clear_inputs,
            outputs=[action_input, context_input, license_input, quick_actions, 
                    oss_results_html, enterprise_results_html, comparison_html, trial_output],
            queue=False
        )
        
        quick_actions.change(
            fn=update_quick_action,
            inputs=[quick_actions],
            outputs=[action_input, context_input],
            queue=False
        )
        
        scenario_select.change(
            fn=update_scenario,
            inputs=[scenario_select],
            outputs=[action_input, context_input],
            queue=False
        )
        
        trial_btn.click(
            fn=generate_trial_license,
            inputs=[trial_email],
            outputs=[trial_output],
            queue=True
        )
        
        # Pre-load with demo scenario
        demo.load(
            fn=lambda: process_action(
                "database_drop",
                "DROP DATABASE production CASCADE",
                '{"environment": "production", "criticality": "high"}',
                "",
                "High Risk"
            ),
            outputs=[oss_results_html, enterprise_results_html, comparison_html, 
                    stats_display, license_status, gr.JSON(visible=False), gr.JSON(visible=False)],
            queue=True
        )
    
    return demo

# Main execution
if __name__ == "__main__":
    print("=" * 60)
    print("πŸš€ Starting ARF 3.3.9 Hugging Face Spaces Demo")
    print(f"πŸ“¦ ARF Version: {ARF_VERSION}")
    print(f"πŸ€– ARF Available: {ARF_AVAILABLE}")
    print("=" * 60)
    
    demo = create_demo_interface()
    
    # For Hugging Face Spaces, we need to expose the demo
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        debug=False
    )