File size: 38,144 Bytes
bc06c6d
8bcc583
ac052ea
bc06c6d
 
 
 
 
 
 
 
 
 
 
f227c8e
a291916
ac052ea
8bcc583
 
 
bc06c6d
8bcc583
 
 
bc06c6d
8bcc583
ac052ea
8bcc583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a291916
8bcc583
 
 
 
 
 
 
 
 
a291916
8bcc583
 
 
 
 
 
 
 
 
a291916
8bcc583
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
8bcc583
ac052ea
8bcc583
 
ac052ea
 
566b72c
8bcc583
 
ac052ea
8bcc583
 
 
 
ac052ea
8bcc583
 
ac052ea
8bcc583
f227c8e
ac052ea
 
bc06c6d
8bcc583
ac052ea
bc06c6d
8bcc583
ac052ea
a291916
8bcc583
ac052ea
a291916
ac052ea
8bcc583
a291916
ac052ea
8bcc583
a291916
8bcc583
 
 
ac052ea
8bcc583
 
 
ac052ea
 
a291916
 
ac052ea
8bcc583
 
bc06c6d
8bcc583
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc06c6d
8bcc583
ac052ea
 
 
 
 
8bcc583
 
ac052ea
8bcc583
ac052ea
8bcc583
ac052ea
8bcc583
ac052ea
8bcc583
 
 
f227c8e
ac052ea
 
 
 
 
 
 
8bcc583
ac052ea
8bcc583
 
ac052ea
 
 
 
a291916
ac052ea
8bcc583
ac052ea
 
8bcc583
bc06c6d
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a291916
 
8bcc583
 
 
 
a291916
 
ac052ea
 
8bcc583
 
 
 
 
ac052ea
 
a291916
 
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a291916
 
8bcc583
 
 
ac052ea
 
a291916
566b72c
ac052ea
8bcc583
 
 
 
 
 
 
ac052ea
 
8bcc583
 
 
ac052ea
8bcc583
 
 
 
ac052ea
8bcc583
 
 
 
 
ac052ea
 
 
8bcc583
 
 
 
 
 
 
ac052ea
8bcc583
 
 
a291916
ac052ea
 
 
 
8bcc583
ac052ea
a291916
ac052ea
 
 
 
 
 
 
 
a291916
ac052ea
 
 
 
 
8bcc583
ac052ea
 
8bcc583
ac052ea
 
 
 
 
 
 
 
8bcc583
ac052ea
 
 
 
8bcc583
ac052ea
 
 
 
 
 
 
 
 
8bcc583
ac052ea
 
 
 
 
 
a291916
ac052ea
 
 
8bcc583
ac052ea
 
8bcc583
a291916
ac052ea
a291916
8bcc583
ac052ea
 
 
 
 
 
 
 
 
8bcc583
 
 
ac052ea
8bcc583
a291916
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
566b72c
ac052ea
 
 
 
 
bc06c6d
 
ac052ea
 
8bcc583
 
 
 
ac052ea
8bcc583
ac052ea
 
 
8bcc583
ac052ea
8bcc583
ac052ea
 
 
8bcc583
ac052ea
 
 
8bcc583
ac052ea
 
 
 
 
 
8bcc583
ac052ea
 
 
 
 
 
8bcc583
ac052ea
 
 
 
 
 
8bcc583
 
bc06c6d
f227c8e
ac052ea
8bcc583
ac052ea
 
8bcc583
bc06c6d
ac052ea
8bcc583
ac052ea
 
 
 
f227c8e
8bcc583
ac052ea
 
 
f227c8e
8bcc583
ac052ea
 
 
f227c8e
8bcc583
ac052ea
 
 
a291916
 
bc06c6d
 
ac052ea
bc06c6d
566b72c
ac052ea
 
 
 
 
bc06c6d
8bcc583
ac052ea
8bcc583
f227c8e
ac052ea
 
f227c8e
8bcc583
ac052ea
8bcc583
 
ac052ea
 
bc06c6d
8bcc583
ac052ea
8bcc583
ac052ea
 
 
bc06c6d
f227c8e
ac052ea
a291916
ac052ea
 
bc06c6d
 
ac052ea
 
 
 
 
 
 
8bcc583
ac052ea
 
8bcc583
ac052ea
 
 
8bcc583
 
f227c8e
ac052ea
566b72c
a291916
ac052ea
8bcc583
a291916
ac052ea
f227c8e
ac052ea
 
f227c8e
ac052ea
 
a291916
 
8bcc583
ac052ea
 
a291916
ac052ea
8bcc583
a291916
ac052ea
8bcc583
ac052ea
 
 
f227c8e
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a291916
ac052ea
 
 
 
 
f227c8e
ac052ea
 
 
 
 
 
 
f227c8e
8bcc583
 
ac052ea
8bcc583
ac052ea
 
 
8bcc583
 
 
 
ac052ea
 
 
8bcc583
 
f227c8e
ac052ea
f227c8e
8bcc583
ac052ea
 
 
 
 
 
8bcc583
 
 
ac052ea
8bcc583
 
 
 
ac052ea
 
8bcc583
ac052ea
 
 
 
8bcc583
ac052ea
 
 
 
 
 
 
 
 
566b72c
 
f227c8e
ac052ea
 
 
8bcc583
 
ac052ea
 
8bcc583
 
 
 
ac052ea
8bcc583
 
 
 
 
 
ac052ea
8bcc583
 
 
 
 
 
 
 
 
 
 
 
 
ac052ea
8bcc583
ac052ea
 
 
8bcc583
f227c8e
8bcc583
 
 
 
 
ac052ea
 
 
 
 
 
8bcc583
 
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f227c8e
566b72c
8bcc583
 
 
ac052ea
 
8bcc583
f227c8e
ac052ea
 
8bcc583
 
ac052ea
 
8bcc583
f227c8e
8bcc583
 
bc06c6d
8bcc583
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
8bcc583
 
ac052ea
 
8bcc583
 
 
ac052ea
 
 
 
8bcc583
ac052ea
 
8bcc583
 
 
 
 
ac052ea
 
 
 
8bcc583
ac052ea
8bcc583
 
 
 
 
 
ac052ea
 
 
 
 
 
8bcc583
ac052ea
 
 
8bcc583
ac052ea
 
 
8bcc583
ac052ea
 
 
8bcc583
 
 
 
 
 
ac052ea
 
 
bc06c6d
ac052ea
 
 
f227c8e
ac052ea
8bcc583
ac052ea
 
8bcc583
a291916
f227c8e
ac052ea
f227c8e
ac052ea
 
a291916
 
 
ac052ea
 
 
a291916
bc06c6d
8bcc583
a291916
8bcc583
 
a291916
f227c8e
ac052ea
 
 
 
 
 
566b72c
bc06c6d
ac052ea
 
 
 
 
 
bc06c6d
a291916
bc06c6d
 
 
 
8bcc583
 
 
 
bc06c6d
ac052ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ARF 3.3.9 Demo - Psychology-Optimized Version
Fixed with proper error handling
"""

import gradio as gr
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import json
import time
import uuid
import hashlib
import random
import traceback
import sys
from typing import Dict, List, Any, Tuple, Optional
from dataclasses import dataclass
from enum import Enum
import re

print("=" * 70)
print("🧠 ARF 3.3.9 DEMO - Psychology-Optimized Edition")
print("=" * 70)

# ============================================================================
# ENUMS AND DATA CLASSES
# ============================================================================

class RiskLevel(str, Enum):
    CRITICAL = "CRITICAL"
    HIGH = "HIGH"
    MEDIUM = "MEDIUM"
    LOW = "LOW"
    SAFE = "SAFE"

class EnforcementLevel(str, Enum):
    ADVISORY = "ADVISORY"
    HUMAN_APPROVAL = "HUMAN_APPROVAL"
    AUTONOMOUS = "AUTONOMOUS"
    FULL_MECHANICAL = "FULL_MECHANICAL"

class LicenseTier(str, Enum):
    TRIAL = "TRIAL"
    STARTER = "STARTER"
    PROFESSIONAL = "PROFESSIONAL"
    ENTERPRISE = "ENTERPRISE"

@dataclass
class RiskAssessment:
    score: float
    level: RiskLevel
    confidence: float
    factors: Dict[str, float]
    
    @property
    def color(self) -> str:
        return {
            RiskLevel.CRITICAL: "#D32F2F",
            RiskLevel.HIGH: "#F44336",
            RiskLevel.MEDIUM: "#FF9800",
            RiskLevel.LOW: "#4CAF50",
            RiskLevel.SAFE: "#2E7D32"
        }[self.level]
    
    @property
    def icon(self) -> str:
        return {
            RiskLevel.CRITICAL: "πŸ”₯",
            RiskLevel.HIGH: "⚠️",
            RiskLevel.MEDIUM: "πŸ”Ά",
            RiskLevel.LOW: "βœ…",
            RiskLevel.SAFE: "πŸ›‘οΈ"
        }[self.level]

@dataclass
class GateResult:
    name: str
    passed: bool
    message: str
    required: bool = True
    weight: float = 1.0
    
    @property
    def color(self) -> str:
        return "#4CAF50" if self.passed else "#F44336"
    
    @property
    def icon(self) -> str:
        return "βœ…" if self.passed else "❌"

# ============================================================================
# SIMPLIFIED BUT ROBUST ENGINE
# ============================================================================

class ARFEngine:
    """Simplified but robust ARF engine"""
    
    def __init__(self):
        self.stats = {
            "total_processed": 0,
            "blocked_actions": 0,
            "autonomous_executions": 0,
            "avg_processing_time": 0.0
        }
        print("βœ… ARF Engine initialized")
    
    def assess_action(self, action: str, context: Dict, license_key: str = None) -> Dict:
        """Assess an action with realistic scoring"""
        start_time = time.time()
        
        # 1. Risk Assessment
        risk = self._assess_risk(action, context)
        
        # 2. Policy Evaluation
        policy_result = self._evaluate_policies(action, context, risk.score)
        
        # 3. License Validation
        license_info = self._validate_license(license_key)
        
        # 4. Gate Evaluation
        gate_results = self._evaluate_gates(risk, policy_result, license_info)
        
        # 5. Generate results
        processing_time = time.time() - start_time
        
        # Update stats
        self._update_stats(policy_result, gate_results, processing_time)
        
        return {
            "timestamp": datetime.now().isoformat(),
            "action": action,
            "risk_assessment": risk,
            "policy_result": policy_result,
            "license_info": license_info,
            "gate_results": gate_results,
            "processing_time": round(processing_time, 4),
            "recommendation": self._generate_recommendation(policy_result, gate_results, license_info)
        }
    
    def _assess_risk(self, action: str, context: Dict) -> RiskAssessment:
        """Assess risk with realistic scoring"""
        action_lower = action.lower()
        
        # Calculate risk factors
        destructiveness = 0.3
        if "drop" in action_lower and "database" in action_lower:
            destructiveness = 0.95
        elif "delete" in action_lower:
            destructiveness = 0.85
        elif "truncate" in action_lower:
            destructiveness = 0.80
        
        complexity = min(0.8, len(action.split()) * 0.05)
        
        env = context.get("environment", "development")
        environment_risk = {
            "production": 0.8,
            "staging": 0.5,
            "testing": 0.3,
            "development": 0.2
        }.get(env, 0.5)
        
        # Weighted risk score
        risk_score = (
            destructiveness * 0.4 +
            complexity * 0.2 +
            environment_risk * 0.4
        )
        
        # Determine risk level
        if risk_score >= 0.8:
            level = RiskLevel.CRITICAL
        elif risk_score >= 0.6:
            level = RiskLevel.HIGH
        elif risk_score >= 0.4:
            level = RiskLevel.MEDIUM
        elif risk_score >= 0.2:
            level = RiskLevel.LOW
        else:
            level = RiskLevel.SAFE
        
        # Confidence (higher for clear patterns)
        confidence = 0.8
        if "drop database" in action_lower:
            confidence = 0.95
        elif "delete from" in action_lower:
            confidence = 0.90
        
        return RiskAssessment(
            score=round(risk_score, 3),
            level=level,
            confidence=round(confidence, 3),
            factors={
                "destructiveness": destructiveness,
                "complexity": complexity,
                "environment": environment_risk
            }
        )
    
    def _evaluate_policies(self, action: str, context: Dict, risk_score: float) -> Dict:
        """Evaluate against safety policies"""
        violations = []
        
        # Policy 1: No destructive operations in production without approval
        if ("drop" in action.lower() or "delete" in action.lower()) and context.get("environment") == "production":
            violations.append({
                "policy": "Destructive Operation Prevention",
                "severity": "CRITICAL",
                "action": "BLOCK"
            })
        
        # Policy 2: High risk actions need review
        if risk_score > 0.7 and context.get("environment") == "production":
            violations.append({
                "policy": "High Risk Review Required",
                "severity": "HIGH",
                "action": "REQUIRE_APPROVAL"
            })
        
        return {
            "violations": violations,
            "blocked": any(v["action"] == "BLOCK" for v in violations),
            "requires_approval": any(v["action"] == "REQUIRE_APPROVAL" for v in violations),
            "total_violations": len(violations)
        }
    
    def _validate_license(self, license_key: str = None) -> Dict:
        """Validate license key"""
        if not license_key:
            return {
                "tier": None,
                "valid": False,
                "name": "OSS Edition",
                "enforcement": "ADVISORY",
                "message": "πŸ”΅ Using ARF OSS (Open Source)"
            }
        
        if license_key.startswith("ARF-"):
            if "TRIAL" in license_key:
                return {
                    "tier": "TRIAL",
                    "valid": True,
                    "name": "Trial",
                    "enforcement": "ADVISORY",
                    "message": "🎁 Trial License Active (14 days)"
                }
            elif "PRO" in license_key:
                return {
                    "tier": "PROFESSIONAL",
                    "valid": True,
                    "name": "Professional",
                    "enforcement": "AUTONOMOUS",
                    "message": "βœ… Professional License Active"
                }
        
        return {
            "tier": None,
            "valid": False,
            "name": "Invalid",
            "enforcement": "ADVISORY",
            "message": "❌ Invalid License Key"
        }
    
    def _evaluate_gates(self, risk: RiskAssessment, policy: Dict, license: Dict) -> List[GateResult]:
        """Evaluate mechanical gates"""
        gates = []
        
        # Gate 1: License Validation
        gates.append(GateResult(
            name="License Validation",
            passed=license.get("valid", False),
            message=license.get("message", "No license"),
            required=True
        ))
        
        # Gate 2: Risk Threshold
        risk_threshold = 0.8 if license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"] else 0.7
        gates.append(GateResult(
            name="Risk Assessment",
            passed=risk.score <= risk_threshold,
            message=f"Risk {risk.score:.1%} ≀ {risk_threshold:.0%} threshold",
            required=True
        ))
        
        # Gate 3: Confidence Threshold
        gates.append(GateResult(
            name="Confidence Threshold",
            passed=risk.confidence >= 0.7,
            message=f"Confidence {risk.confidence:.1%} β‰₯ 70%",
            required=True
        ))
        
        # Gate 4: Policy Compliance
        gates.append(GateResult(
            name="Policy Compliance",
            passed=not policy.get("blocked", False),
            message=f"{policy.get('total_violations', 0)} policy violations",
            required=True
        ))
        
        return gates
    
    def _generate_recommendation(self, policy: Dict, gates: List[GateResult], license: Dict) -> str:
        """Generate recommendation"""
        if policy.get("blocked"):
            return "🚫 BLOCKED: Action violates safety policies"
        
        all_gates_passed = all(g.passed for g in gates if g.required)
        
        if not license.get("valid"):
            return "πŸ”΅ OSS ADVISORY: Human review recommended"
        elif all_gates_passed and license.get("tier") in ["PROFESSIONAL", "ENTERPRISE"]:
            return "🟑 ENTERPRISE APPROVED: Autonomous execution permitted"
        elif all_gates_passed and license.get("tier") == "STARTER":
            return "πŸ‘€ HUMAN APPROVAL: Gates passed, awaiting confirmation"
        else:
            return "⚠️ REVIEW REQUIRED: Additional validation needed"
    
    def _update_stats(self, policy: Dict, gates: List[GateResult], processing_time: float):
        """Update statistics"""
        self.stats["total_processed"] += 1
        if policy.get("blocked"):
            self.stats["blocked_actions"] += 1
        
        if all(g.passed for g in gates if g.required):
            self.stats["autonomous_executions"] += 1
        
        # Update average processing time
        self.stats["avg_processing_time"] = (
            self.stats["avg_processing_time"] * 0.9 + processing_time * 0.1
        )
    
    def get_stats(self) -> Dict:
        """Get statistics with safe defaults"""
        stats = self.stats.copy()
        
        # Calculate derived stats with error handling
        total = stats.get("total_processed", 0)
        blocked = stats.get("blocked_actions", 0)
        autonomous = stats.get("autonomous_executions", 0)
        
        stats["blocked_percentage"] = round(blocked / total * 100, 1) if total > 0 else 0.0
        stats["autonomous_percentage"] = round(autonomous / total * 100, 1) if total > 0 else 0.0
        stats["processing_speed"] = f"{stats.get('avg_processing_time', 0)*1000:.0f}ms"
        
        # Add default values for any missing keys
        defaults = {
            "risk_distribution": {"CRITICAL": 0, "HIGH": 0, "MEDIUM": 0, "LOW": 0, "SAFE": 0},
            "system_health": "βœ… Optimal",
            "license_distribution": {"OSS": 0, "TRIAL": 0, "ENTERPRISE": 0}
        }
        
        for key, value in defaults.items():
            if key not in stats:
                stats[key] = value
        
        return stats
    
    def generate_trial_license(self, email: str) -> Dict:
        """Generate trial license"""
        if not email or "@" not in email:
            return {
                "success": False,
                "message": "Please enter a valid email address"
            }
        
        license_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}"
        
        return {
            "success": True,
            "license_key": license_key,
            "message": "πŸŽ‰ 14-Day Trial License Generated!",
            "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
            "features": [
                "Mechanical gate evaluation",
                "Enterprise dashboard",
                "Basic audit trail"
            ]
        }

# ============================================================================
# DEMO DATA
# ============================================================================

DEMO_SCENARIOS = [
    {
        "id": "high_risk",
        "name": "πŸ”₯ High-Risk Database Operation",
        "action": "DROP DATABASE production_users CASCADE",
        "context": {"environment": "production", "criticality": "critical"}
    },
    {
        "id": "safe_deploy", 
        "name": "βœ… Safe Service Deployment",
        "action": "deploy_service payment_api:v2.3.1 to staging with 25% canary",
        "context": {"environment": "staging", "service": "payment_api", "canary": 25}
    },
    {
        "id": "config_change",
        "name": "πŸ”§ Configuration Update",
        "action": "UPDATE config SET timeout_ms=30000 WHERE service='api'",
        "context": {"environment": "production", "service": "api"}
    }
]

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

def create_demo_interface():
    """Create the demo interface"""
    
    # Initialize engine
    arf_engine = ARFEngine()
    
    # Get initial stats with error handling
    try:
        stats = arf_engine.get_stats()
    except Exception as e:
        print(f"Error getting stats: {e}")
        stats = {
            "total_processed": 0,
            "blocked_percentage": 0.0,
            "autonomous_percentage": 0.0,
            "processing_speed": "0ms"
        }
    
    # Safely get values with defaults
    total_processed = stats.get("total_processed", 0)
    blocked_percentage = stats.get("blocked_percentage", 0.0)
    autonomous_percentage = stats.get("autonomous_percentage", 0.0)
    processing_speed = stats.get("processing_speed", "0ms")
    
    with gr.Blocks(
        title="ARF 3.3.9 - OSS vs Enterprise Demo",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1400px;
            margin: 0 auto;
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
        }
        .demo-card {
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .oss-card {
            border: 2px solid #1E88E5;
            background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 100%);
        }
        .enterprise-card {
            border: 2px solid #FFB300;
            background: linear-gradient(135deg, #FFF8E1 0%, #FFECB3 100%);
        }
        .stat-card {
            background: white;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .gate-passed {
            background: #E8F5E9;
            border-left: 4px solid #4CAF50;
            padding: 10px;
            margin: 5px 0;
            border-radius: 4px;
        }
        .gate-failed {
            background: #FFEBEE;
            border-left: 4px solid #F44336;
            padding: 10px;
            margin: 5px 0;
            border-radius: 4px;
        }
        """
    ) as demo:
        
        # Header
        gr.Markdown("""
        # πŸ€– Agentic Reliability Framework (ARF) 3.3.9
        ### From Advisory to Mechanical Enforcement
        """)
        
        # Statistics
        gr.Markdown(f"""
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 20px 0;">
            <div class="stat-card">
                <div style="font-size: 0.9em; color: #1E88E5; margin-bottom: 5px;">Total Assessments</div>
                <div style="font-size: 2em; font-weight: bold; color: #1E88E5;">{total_processed}</div>
            </div>
            
            <div class="stat-card">
                <div style="font-size: 0.9em; color: #F44336; margin-bottom: 5px;">Risks Blocked</div>
                <div style="font-size: 2em; font-weight: bold; color: #F44336;">{blocked_percentage}%</div>
            </div>
            
            <div class="stat-card">
                <div style="font-size: 0.9em; color: #4CAF50; margin-bottom: 5px;">Autonomous Rate</div>
                <div style="font-size: 2em; font-weight: bold; color: #4CAF50;">{autonomous_percentage}%</div>
            </div>
            
            <div class="stat-card">
                <div style="font-size: 0.9em; color: #FF9800; margin-bottom: 5px;">Processing Speed</div>
                <div style="font-size: 2em; font-weight: bold; color: #FF9800;">{processing_speed}</div>
            </div>
        </div>
        """)
        
        # Main controls
        with gr.Row():
            with gr.Column(scale=2):
                # Scenario selection
                scenario_select = gr.Dropdown(
                    choices=[s["name"] for s in DEMO_SCENARIOS],
                    label="Select Demo Scenario",
                    value=DEMO_SCENARIOS[0]["name"]
                )
                
                # Action input
                action_input = gr.Textbox(
                    label="Action to Evaluate",
                    value=DEMO_SCENARIOS[0]["action"],
                    lines=2
                )
                
                # Context input
                context_input = gr.Textbox(
                    label="Context (JSON)",
                    value=json.dumps(DEMO_SCENARIOS[0]["context"], indent=2),
                    lines=3
                )
                
                # License input
                license_input = gr.Textbox(
                    label="Enterprise License Key (Optional)",
                    placeholder="Enter ARF-TRIAL-XXXXXXX or leave blank for OSS",
                    value=""
                )
                
                # Buttons
                with gr.Row():
                    process_btn = gr.Button("πŸš€ Process Action", variant="primary", size="lg")
                    clear_btn = gr.Button("πŸ”„ Clear", variant="secondary")
            
            with gr.Column(scale=1):
                # Quick examples
                gr.Markdown("### Quick Examples")
                quick_examples = gr.Radio(
                    choices=["High Risk", "Medium Risk", "Low Risk"],
                    label="Risk Level",
                    value="High Risk"
                )
                
                # License status
                gr.Markdown("### License Status")
                license_status = gr.HTML("""
                <div style="background: #E3F2FD; padding: 15px; border-radius: 8px; text-align: center;">
                    <div style="color: #1E88E5; font-weight: bold; margin-bottom: 5px;">πŸ”΅ ARF OSS Edition</div>
                    <div style="color: #666; font-size: 0.9em;">Advisory Mode - No license required</div>
                </div>
                """)
        
        # Results
        with gr.Row():
            with gr.Column(scale=1):
                oss_output = gr.HTML(label="πŸ”΅ ARF OSS Results")
            
            with gr.Column(scale=1):
                enterprise_output = gr.HTML(label="🟑 ARF Enterprise Results")
        
        # Comparison
        comparison_output = gr.HTML(label="πŸ“Š Side-by-Side Comparison")
        
        # Trial section
        with gr.Accordion("🎁 Get 14-Day Trial License", open=False):
            with gr.Row():
                with gr.Column(scale=1):
                    email_input = gr.Textbox(
                        label="Work Email",
                        placeholder="you@company.com"
                    )
                    trial_btn = gr.Button("Get Trial License", variant="primary")
                
                with gr.Column(scale=2):
                    trial_output = gr.JSON(label="Your Trial License")
        
        # Functions
        def process_action(scenario_name, action_text, context_text, license_key, quick_example):
            """Process an action"""
            try:
                # Update based on quick example
                if quick_example == "High Risk":
                    action_text = "DELETE FROM users WHERE created_at < '2023-01-01'"
                    context_text = '{"environment": "production"}'
                elif quick_example == "Medium Risk":
                    action_text = "ALTER TABLE payments ADD COLUMN metadata JSONB"
                    context_text = '{"environment": "staging"}'
                elif quick_example == "Low Risk":
                    action_text = "SELECT COUNT(*) FROM logs"
                    context_text = '{"environment": "development"}'
                
                # Use scenario if selected
                for scenario in DEMO_SCENARIOS:
                    if scenario["name"] == scenario_name:
                        action_text = scenario["action"]
                        context_text = json.dumps(scenario["context"])
                        break
                
                # Parse context
                try:
                    context = json.loads(context_text) if context_text.strip() else {}
                except:
                    context = {"environment": "production"}
                
                # Process action
                result = arf_engine.assess_action(action_text, context, license_key)
                
                # Create displays
                oss_html = create_oss_display(result)
                enterprise_html = create_enterprise_display(result)
                comparison_html = create_comparison_display(result)
                
                # Update license status
                license_info = result["license_info"]
                if license_info.get("valid"):
                    status_html = f"""
                    <div style="background: #E8F5E9; padding: 15px; border-radius: 8px; text-align: center;">
                        <div style="color: #2E7D32; font-weight: bold; margin-bottom: 5px;">βœ… {license_info['name']} License</div>
                        <div style="color: #666; font-size: 0.9em;">{license_info['message']}</div>
                    </div>
                    """
                else:
                    status_html = """
                    <div style="background: #E3F2FD; padding: 15px; border-radius: 8px; text-align: center;">
                        <div style="color: #1E88E5; font-weight: bold; margin-bottom: 5px;">πŸ”΅ ARF OSS Edition</div>
                        <div style="color: #666; font-size: 0.9em;">Advisory Mode - No license required</div>
                    </div>
                    """
                
                return oss_html, enterprise_html, comparison_html, status_html
                
            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>
                </div>
                """
                return error_html, error_html, error_html, ""
        
        def create_oss_display(result):
            """Create OSS display"""
            risk = result["risk_assessment"]
            policy = result["policy_result"]
            
            return f"""
            <div class="demo-card oss-card">
                <h3 style="margin: 0 0 15px 0; color: #1E88E5;">πŸ”΅ ARF OSS 3.3.9</h3>
                
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: #1E88E5;">Reliability</div>
                        <div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{(1-risk.score):.1%}</div>
                    </div>
                    
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: {risk.color};">Risk Level</div>
                        <div style="font-size: 1.5em; font-weight: bold; color: {risk.color};">{risk.level.value}</div>
                    </div>
                    
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: #1E88E5;">Confidence</div>
                        <div style="font-size: 1.5em; font-weight: bold; color: #1E88E5;">{risk.confidence:.1%}</div>
                    </div>
                </div>
                
                <div style="background: white; padding: 15px; border-radius: 8px; margin-bottom: 15px; border-left: 4px solid {risk.color};">
                    <h4 style="margin: 0 0 10px 0; color: #333;">πŸ’‘ Recommendation</h4>
                    <p style="margin: 0; font-size: 1.1em; font-weight: 500;">{result['recommendation']}</p>
                </div>
                
                <div style="background: #FFF3E0; padding: 15px; border-radius: 8px;">
                    <h4 style="margin: 0 0 10px 0; color: #E65100;">⚠️ OSS Limitations</h4>
                    <ul style="margin: 0; padding-left: 20px; color: #E65100;">
                        <li>Human decision required for all actions</li>
                        <li>No mechanical enforcement</li>
                        <li>{policy['total_violations']} policy violation(s) detected</li>
                        <li>Processing time: {result['processing_time']}s</li>
                    </ul>
                </div>
            </div>
            """
        
        def create_enterprise_display(result):
            """Create Enterprise display"""
            risk = result["risk_assessment"]
            gates = result["gate_results"]
            license_info = result["license_info"]
            
            # Calculate gate progress
            required_gates = [g for g in gates if g.required]
            passed_required = sum(1 for g in required_gates if g.passed)
            
            # Create gates HTML
            gates_html = ""
            for gate in gates:
                gate_class = "gate-passed" if gate.passed else "gate-failed"
                gates_html += f"""
                <div class="{gate_class}">
                    <div style="display: flex; align-items: center;">
                        <span style="font-size: 20px; margin-right: 10px;">{gate.icon}</span>
                        <div>
                            <div style="font-weight: 500;">{gate.name}</div>
                            <div style="font-size: 0.9em; color: #666;">{gate.message}</div>
                        </div>
                    </div>
                </div>
                """
            
            return f"""
            <div class="demo-card enterprise-card">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0; color: #FF8F00;">🟑 ARF Enterprise 3.3.9</h3>
                    <span style="background: rgba(255, 179, 0, 0.1); padding: 5px 10px; border-radius: 15px; color: #FF8F00; font-weight: 500;">
                        {license_info.get('name', 'OSS')}
                    </span>
                </div>
                
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 20px;">
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: #FF8F00;">License Tier</div>
                        <div style="font-size: 1.2em; font-weight: bold; color: #FF8F00;">{license_info.get('name', 'OSS')}</div>
                    </div>
                    
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: #FF8F00;">Gates Passed</div>
                        <div style="font-size: 1.5em; font-weight: bold; color: #FF8F00;">{passed_required}/{len(required_gates)}</div>
                    </div>
                    
                    <div style="text-align: center; padding: 10px; background: white; border-radius: 6px;">
                        <div style="font-size: 0.9em; color: #FF8F00;">Enforcement</div>
                        <div style="font-size: 1.1em; font-weight: bold; color: #FF8F00;">
                            {license_info.get('enforcement', 'ADVISORY').replace('_', ' ').title()}
                        </div>
                    </div>
                </div>
                
                <div style="margin-bottom: 20px;">
                    <h4 style="margin: 0 0 10px 0; color: #FF8F00;">Mechanical Gates</h4>
                    {gates_html}
                </div>
                
                <div style="background: #E8F5E9; padding: 15px; border-radius: 8px;">
                    <h4 style="margin: 0 0 10px 0; color: #2E7D32;">πŸš€ Enterprise Benefits</h4>
                    <ul style="margin: 0; padding-left: 20px; color: #2E7D32;">
                        <li>Mechanical enforcement with automated gates</li>
                        <li>Processing time: {result['processing_time']}s</li>
                        <li>{license_info.get('message', 'Enterprise-grade protection')}</li>
                    </ul>
                </div>
            </div>
            """
        
        def create_comparison_display(result):
            """Create comparison display"""
            policy = result["policy_result"]
            gates = result["gate_results"]
            license_info = result["license_info"]
            
            oss_can_execute = not policy.get("blocked", False)
            all_gates_passed = all(g.passed for g in gates if g.required)
            
            if all_gates_passed and license_info.get("valid"):
                enterprise_auth = "AUTONOMOUS_EXECUTION"
            elif license_info.get("valid"):
                enterprise_auth = "ADVISORY_ONLY"
            else:
                enterprise_auth = "OSS_ONLY"
            
            return f"""
            <div class="demo-card" style="background: white;">
                <h3 style="margin: 0 0 20px 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;">
                    <div style="text-align: center;">
                        <div style="background: #E3F2FD; padding: 20px; border-radius: 10px; margin-bottom: 15px;">
                            <h4 style="color: #1E88E5; margin: 0 0 10px 0;">πŸ”΅ OSS 3.3.9</h4>
                            <div style="font-size: 48px; color: #1E88E5; margin-bottom: 10px;">
                                {'⚠️' if not oss_can_execute else 'βœ…'}
                            </div>
                            <div style="font-weight: bold; color: {'#F44336' if not oss_can_execute else '#4CAF50'};">
                                {'Advisory Only' if not oss_can_execute else 'Can Execute'}
                            </div>
                        </div>
                    </div>
                    
                    <div style="text-align: center;">
                        <div style="background: #FFF8E1; padding: 20px; border-radius: 10px; margin-bottom: 15px;">
                            <h4 style="color: #FFB300; margin: 0 0 10px 0;">🟑 Enterprise</h4>
                            <div style="font-size: 48px; color: #FFB300; margin-bottom: 10px;">
                                {'βœ…' if enterprise_auth == 'AUTONOMOUS_EXECUTION' else 'πŸ‘€' if enterprise_auth == 'ADVISORY_ONLY' else 'πŸ”΅'}
                            </div>
                            <div style="font-weight: bold; color: {'#4CAF50' if enterprise_auth == 'AUTONOMOUS_EXECUTION' else '#FF9800' if enterprise_auth == 'ADVISORY_ONLY' else '#1E88E5'};">
                                {enterprise_auth.replace('_', ' ').title()}
                            </div>
                        </div>
                    </div>
                </div>
                
                <div style="background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); padding: 20px; border-radius: 10px;">
                    <h4 style="text-align: center; margin-top: 0; color: #333;">🎯 Enterprise Value Proposition</h4>
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin: 15px 0;">
                        <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
                            <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Risk Reduction</div>
                            <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">92%</div>
                        </div>
                        <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
                            <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">Decision Speed</div>
                            <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">100x</div>
                        </div>
                        <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
                            <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">False Positives</div>
                            <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">-85%</div>
                        </div>
                        <div style="text-align: center; padding: 15px; background: white; border-radius: 8px;">
                            <div style="font-size: 0.9em; color: #666; margin-bottom: 5px;">OpEx Reduction</div>
                            <div style="font-size: 1.8em; font-weight: bold; color: #4CAF50;">-75%</div>
                        </div>
                    </div>
                </div>
            </div>
            """
        
        def generate_trial(email):
            """Generate trial license"""
            return arf_engine.generate_trial_license(email)
        
        def clear_inputs():
            """Clear all inputs"""
            return DEMO_SCENARIOS[0]["action"], json.dumps(DEMO_SCENARIOS[0]["context"], indent=2), "", "High Risk", "", "", "", ""
        
        def update_scenario(scenario_name):
            """Update inputs based on scenario"""
            for scenario in DEMO_SCENARIOS:
                if scenario["name"] == scenario_name:
                    return scenario["action"], json.dumps(scenario["context"], indent=2)
            return "", "{}"
        
        # Connect events
        process_btn.click(
            process_action,
            [scenario_select, action_input, context_input, license_input, quick_examples],
            [oss_output, enterprise_output, comparison_output, license_status]
        )
        
        clear_btn.click(
            clear_inputs,
            outputs=[action_input, context_input, license_input, quick_examples, oss_output, enterprise_output, comparison_output, license_status]
        )
        
        scenario_select.change(
            update_scenario,
            [scenario_select],
            [action_input, context_input]
        )
        
        trial_btn.click(
            generate_trial,
            [email_input],
            [trial_output]
        )
        
        # Initial load
        demo.load(
            lambda: process_action(
                DEMO_SCENARIOS[0]["name"],
                DEMO_SCENARIOS[0]["action"],
                json.dumps(DEMO_SCENARIOS[0]["context"]),
                "",
                "High Risk"
            ),
            outputs=[oss_output, enterprise_output, comparison_output, license_status]
        )
    
    return demo

# ============================================================================
# MAIN EXECUTION
# ============================================================================

if __name__ == "__main__":
    print("\nπŸš€ Starting ARF 3.3.9 Demo")
    
    try:
        demo = create_demo_interface()
        demo.launch(
            server_name="0.0.0.0",
            server_port=7860,
            share=False,
            debug=False,
            show_error=True
        )
    except Exception as e:
        print(f"❌ Error launching demo: {e}")
        traceback.print_exc()
        
        # Fallback minimal interface
        with gr.Blocks() as fallback:
            gr.Markdown("""
            # πŸ€– ARF 3.3.9 Demo
            The main demo is experiencing technical difficulties.
            
            **Key Value Proposition:**
            - **OSS**: Advisory recommendations only
            - **Enterprise**: Mechanical enforcement with automated gates
            
            **Visit [arf.dev](https://arf.dev) for the full demo.**
            """)
        fallback.launch()