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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
"""
Hugging Face Spaces Demo for Agentic Reliability Framework (ARF)
Version: 3.3.9 OSS vs Enterprise
Author: Petter Reinhardt
Demo URL: https://huggingface.co/spaces/petter2025/agentic-reliability-framework
"""

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
import hashlib
import random

# Import REAL ARF 3.3.9 OSS components
from agentic_reliability_framework.models import (
    ReliabilityEvent,
    HealingPolicy,
    PolicyAction,
    AgentContext,
    AnomalyScore,
    ReliabilityScore
)

from agentic_reliability_framework.healing_policies import (
    PolicyEngine,
    PolicyViolation,
    HealingAction
)

from agentic_reliability_framework.engine.reliability import (
    ReliabilityEngine,
    ConfidenceScore,
    RiskAssessment
)

# Mock Enterprise Components (for demonstration)
class MockEnterpriseLicenseManager:
    """Simulates enterprise license validation with mechanical gates"""
    
    def __init__(self):
        self.license_tiers = {
            "trial": {"max_agents": 3, "enforcement": "advisory", "price": 0},
            "starter": {"max_agents": 10, "enforcement": "human_approval", "price": 2000},
            "professional": {"max_agents": 50, "enforcement": "autonomous", "price": 5000},
            "enterprise": {"max_agents": 1000, "enforcement": "full_mechanical", "price": 15000}
        }
        self.active_licenses = {}
    
    def validate_license(self, license_key: str, action_type: str, risk_score: float) -> Dict:
        """Validate enterprise license and mechanical gate requirements"""
        license_data = self.active_licenses.get(license_key, {"tier": "trial", "expires": datetime.now() + timedelta(days=14)})
        tier = license_data["tier"]
        tier_info = self.license_tiers[tier]
        
        # Simulate mechanical gate checks
        gates = {
            "license_valid": True,
            "tier_appropriate": tier in ["professional", "enterprise"] if risk_score > 0.7 else True,
            "within_limits": True,
            "payment_current": True
        }
        
        passed_gates = sum(gates.values())
        total_gates = len(gates)
        
        return {
            "valid": True,
            "tier": tier,
            "enforcement_level": tier_info["enforcement"],
            "gates_passed": passed_gates,
            "total_gates": total_gates,
            "gates": gates,
            "can_execute": tier_info["enforcement"] != "advisory" and passed_gates == total_gates
        }

class MockExecutionAuthorityService:
    """Simulates mechanical gate enforcement for Enterprise"""
    
    def __init__(self):
        self.gate_definitions = {
            "license_validation": {"weight": 0.3, "required": True},
            "confidence_threshold": {"weight": 0.25, "required": True},
            "risk_assessment": {"weight": 0.25, "required": True},
            "rollback_feasibility": {"weight": 0.1, "required": False},
            "admin_approval": {"weight": 0.1, "required": tier == "starter"},
            "compliance_check": {"weight": 0.1, "required": tier == "enterprise"}
        }
    
    def evaluate_gates(self, action_data: Dict, license_tier: str) -> Dict:
        """Evaluate all mechanical gates for an action"""
        results = {}
        confidence = action_data.get("confidence", 0.5)
        risk_score = action_data.get("risk_score", 0.5)
        
        # Evaluate each gate
        results["license_validation"] = {
            "passed": True,
            "message": "Professional license validated",
            "details": {"license_tier": license_tier}
        }
        
        results["confidence_threshold"] = {
            "passed": confidence >= 0.7,
            "message": f"Confidence {confidence:.2f} β‰₯ 0.70" if confidence >= 0.7 else f"Confidence {confidence:.2f} < 0.70",
            "details": {"threshold": 0.7, "actual": confidence}
        }
        
        results["risk_assessment"] = {
            "passed": risk_score <= 0.8,
            "message": f"Risk {risk_score:.2f} ≀ 0.80" if risk_score <= 0.8 else f"Risk {risk_score:.2f} > 0.80",
            "details": {"threshold": 0.8, "actual": risk_score}
        }
        
        results["rollback_feasibility"] = {
            "passed": True,
            "message": "Rollback plan exists",
            "details": {"rollback_time": "2 minutes"}
        }
        
        if license_tier == "starter":
            results["admin_approval"] = {
                "passed": True,
                "message": "Admin approval granted",
                "details": {"approver": "admin@company.com"}
            }
        
        # Calculate overall gate status
        passed_gates = sum(1 for gate in results.values() if gate["passed"])
        total_gates = len(results)
        
        return {
            "gate_results": results,
            "passed_gates": passed_gates,
            "total_gates": total_gates,
            "all_passed": passed_gates == total_gates,
            "execution_authority": "GRANTED" if passed_gates == total_gates else "DENIED"
        }

class MockAuditService:
    """Simulates enterprise audit trail with differential privacy"""
    
    def __init__(self):
        self.audit_log = []
    
    def log_execution(self, action: str, result: str, user_context: Dict, license_tier: str):
        """Log execution with differential privacy simulation"""
        audit_id = str(uuid.uuid4())
        timestamp = datetime.now().isoformat()
        
        # Add noise for differential privacy (simulated)
        noisy_timestamp = timestamp
        
        log_entry = {
            "audit_id": audit_id,
            "action": action,
            "result": result,
            "timestamp": noisy_timestamp,
            "license_tier": license_tier,
            "user_hash": hashlib.sha256(json.dumps(user_context).encode()).hexdigest()[:16]
        }
        
        self.audit_log.append(log_entry)
        return log_entry

# Demo Configuration
class DemoConfig:
    OSS_THEME = {
        "primary": "#1E88E5",  # Blue
        "secondary": "#64B5F6",
        "background": "#E3F2FD",
        "text": "#1565C0"
    }
    
    ENTERPRISE_THEME = {
        "primary": "#FFB300",  # Gold
        "secondary": "#FFD54F",
        "background": "#FFF8E1",
        "text": "#FF8F00"
    }
    
    SCENARIOS = [
        "database_drop",
        "service_deployment",
        "config_change",
        "user_permission_grant",
        "sensitive_data_access",
        "auto_scaling_adjustment",
        "emergency_rollback"
    ]

# Real ARF OSS Engine Integration
class ARFOSSProcessor:
    """Process actions using real ARF 3.3.9 OSS engine"""
    
    def __init__(self):
        self.policy_engine = PolicyEngine()
        self.reliability_engine = ReliabilityEngine()
        
        # Pre-load some policies for demo
        self._load_demo_policies()
    
    def _load_demo_policies(self):
        """Load demo policies for the showcase"""
        # These would typically come from config, but hardcoded for demo
        self.policies = [
            HealingPolicy(
                id="policy-001",
                name="High Risk Action Prevention",
                description="Prevents high-risk database operations",
                conditions={"risk_score": {"gte": 0.8}},
                action=PolicyAction.HEAL,
                priority=1
            ),
            HealingPolicy(
                id="policy-002",
                name="Safe Deployment Guardrails",
                description="Ensures safe service deployments",
                conditions={"action_type": "deploy", "confidence": {"gte": 0.7}},
                action=PolicyAction.ALLOW,
                priority=2
            )
        ]
    
    def evaluate_action(self, action_description: str, context: Dict = None) -> Dict:
        """Evaluate an action using ARF OSS 3.3.9"""
        start_time = time.time()
        
        # Create a reliability event
        event = ReliabilityEvent(
            event_id=str(uuid.uuid4()),
            agent_id="demo_agent",
            action=action_description,
            timestamp=datetime.now(),
            context=context or {}
        )
        
        # Get reliability score
        reliability_score = self.reliability_engine.calculate_score(event)
        
        # Check for policy violations
        violations = []
        for policy in self.policies:
            violation = self.policy_engine.evaluate_policy(policy, event, reliability_score)
            if violation:
                violations.append(violation)
        
        # Determine recommendation
        risk_level = "High" if reliability_score.overall < 0.3 else "Medium" if reliability_score.overall < 0.7 else "Low"
        
        if violations:
            recommendation = "Block or review action"
            can_execute = False
        else:
            if reliability_score.overall >= 0.8:
                recommendation = "Safe to execute"
                can_execute = True
            elif reliability_score.overall >= 0.6:
                recommendation = "Review recommended"
                can_execute = False
            else:
                recommendation = "High risk - do not execute"
                can_execute = False
        
        processing_time = time.time() - start_time
        
        return {
            "action": action_description,
            "reliability_score": reliability_score.overall,
            "confidence": reliability_score.confidence,
            "risk_score": 1 - reliability_score.overall,
            "risk_level": risk_level,
            "policy_violations": len(violations),
            "violation_details": [str(v) for v in violations[:3]],  # Limit details
            "recommendation": recommendation,
            "can_execute_oss": can_execute,
            "processing_time": processing_time,
            "engine_version": "ARF 3.3.9 OSS",
            "limitation": "Advisory only - human must make final decision"
        }

# Main Demo Application
class ARFDemo:
    """Main demo application for Hugging Face Spaces"""
    
    def __init__(self):
        self.oss_processor = ARFOSSProcessor()
        self.license_manager = MockEnterpriseLicenseManager()
        self.execution_service = MockExecutionAuthorityService()
        self.audit_service = MockAuditService()
        self.user_sessions = {}
        self.demo_scenarios = self._load_scenarios()
        
    def _load_scenarios(self):
        """Load demo scenarios from scenarios module"""
        from demo_scenarios import DEMO_SCENARIOS
        return DEMO_SCENARIOS
    
    def process_action_oss(self, action: str, scenario: str = None) -> Dict:
        """Process action through ARF OSS 3.3.9"""
        if scenario and scenario in self.demo_scenarios:
            action_data = self.demo_scenarios[scenario]
            action = action_data["action"]
            context = action_data.get("context", {})
        else:
            context = {}
        
        return self.oss_processor.evaluate_action(action, context)
    
    def process_action_enterprise(self, action: str, license_key: str, scenario: str = None) -> Dict:
        """Process action through mocked Enterprise system"""
        # First, process through OSS to get baseline
        oss_result = self.process_action_oss(action, scenario)
        
        # Then apply enterprise gates
        license_validation = self.license_manager.validate_license(
            license_key, 
            action, 
            oss_result["risk_score"]
        )
        
        # 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"]
        }
        
        # Evaluate mechanical gates
        gate_evaluation = self.execution_service.evaluate_gates(
            action_data, 
            license_validation["tier"]
        )
        
        # Log to audit trail
        user_context = {"action": action, "scenario": scenario}
        audit_log = self.audit_service.log_execution(
            action,
            gate_evaluation["execution_authority"],
            user_context,
            license_validation["tier"]
        )
        
        # Combine results
        return {
            **oss_result,
            "license_tier": license_validation["tier"],
            "enforcement_level": license_validation["enforcement_level"],
            "gate_results": gate_evaluation["gate_results"],
            "gates_passed": gate_evaluation["passed_gates"],
            "total_gates": gate_evaluation["total_gates"],
            "execution_authority": gate_evaluation["execution_authority"],
            "can_execute_enterprise": gate_evaluation["all_passed"],
            "audit_id": audit_log["audit_id"],
            "engine_version": f"ARF 3.3.9 Enterprise ({license_validation['tier'].title()})",
            "benefit": "Mechanical enforcement - automated decision making"
        }
    
    def generate_trial_license(self, email: str) -> Dict:
        """Generate a trial license for demo purposes"""
        trial_key = f"ARF-TRIAL-{hashlib.sha256(email.encode()).hexdigest()[:8].upper()}"
        
        # Store in mock license manager
        self.license_manager.active_licenses[trial_key] = {
            "tier": "trial",
            "email": email,
            "expires": datetime.now() + timedelta(days=14),
            "created": datetime.now()
        }
        
        # Store user session
        session_id = str(uuid.uuid4())
        self.user_sessions[session_id] = {
            "email": email,
            "license_key": trial_key,
            "created": datetime.now()
        }
        
        return {
            "success": True,
            "license_key": trial_key,
            "expires": (datetime.now() + timedelta(days=14)).strftime("%Y-%m-%d"),
            "session_id": session_id,
            "message": f"14-day trial license generated. Tier: Trial (Advisory mode)"
        }
    
    def upgrade_simulation(self, current_tier: str, target_tier: str, email: str) -> Dict:
        """Simulate upgrade process"""
        price_map = {
            "trial": 0,
            "starter": 2000,
            "professional": 5000,
            "enterprise": 15000
        }
        
        return {
            "current_tier": current_tier,
            "target_tier": target_tier,
            "monthly_price": price_map[target_tier],
            "enforcement_improvement": self._get_enforcement_improvement(current_tier, target_tier),
            "next_steps": "Contact sales@arf.dev for upgrade",
            "estimated_setup": "24 hours"
        }
    
    def _get_enforcement_improvement(self, current: str, target: str) -> str:
        improvements = {
            ("trial", "starter"): "Human-in-the-loop approval",
            ("trial", "professional"): "Autonomous execution for low-risk actions",
            ("trial", "enterprise"): "Full mechanical enforcement with audit",
            ("starter", "professional"): "Remove human bottleneck",
            ("starter", "enterprise"): "Add compliance automation",
            ("professional", "enterprise"): "Enterprise-scale enforcement"
        }
        return improvements.get((current, target), "Enhanced enforcement capabilities")

# Gradio Interface Components
def create_oss_panel(oss_result: Dict) -> gr.Blocks:
    """Create OSS results panel"""
    with gr.Column(variant="panel"):
        gr.Markdown("### πŸ”΅ ARF 3.3.9 OSS (Open Source)")
        
        # Score indicators
        with gr.Row():
            gr.Metric(label="Reliability Score", value=f"{oss_result['reliability_score']:.2%}")
            gr.Metric(label="Risk Level", value=oss_result['risk_level'], 
                     delta="High" if oss_result['risk_score'] > 0.7 else None)
            gr.Metric(label="Confidence", value=f"{oss_result['confidence']:.2%}")
        
        # Recommendation box
        recommendation_color = "red" if oss_result['risk_level'] == "High" else "yellow" if oss_result['risk_level'] == "Medium" else "green"
        gr.HTML(f"""
        <div style='background-color: #E3F2FD; padding: 15px; border-radius: 10px; border-left: 5px solid #{'E53935' if recommendation_color == 'red' else 'FFB300' if recommendation_color == 'yellow' else '43A047'}; margin: 10px 0;'>
            <h4 style='margin-top: 0;'>πŸ’‘ Recommendation</h4>
            <p style='font-size: 16px;'>{oss_result['recommendation']}</p>
            <p style='font-size: 12px; color: #666;'>Processing time: {oss_result['processing_time']:.3f}s</p>
        </div>
        """)
        
        # Limitations
        with gr.Accordion("⚠️ OSS Limitations", open=False):
            gr.Markdown(f"""
            **Advisory Only**: {oss_result['limitation']}
            
            **Policy Violations**: {oss_result['policy_violations']} violation(s) detected
            
            **Execution Authority**: {'βœ… Can execute' if oss_result['can_execute_oss'] else '❌ Cannot execute - human decision required'}
            
            **Version**: {oss_result['engine_version']}
            """)
        
        # Show violation details if any
        if oss_result['policy_violations'] > 0 and oss_result['violation_details']:
            with gr.Accordion(f"πŸ” Policy Violations ({oss_result['policy_violations']})", open=False):
                for i, violation in enumerate(oss_result['violation_details'][:3]):
                    gr.Textbox(f"{i+1}. {violation}", interactive=False, show_copy_button=True)

def create_enterprise_panel(enterprise_result: Dict) -> gr.Blocks:
    """Create Enterprise results panel"""
    with gr.Column(variant="panel"):
        gr.Markdown(f"### 🟑 ARF 3.3.9 Enterprise ({enterprise_result.get('license_tier', 'Trial').title()})")
        
        # License and Gate status
        with gr.Row():
            gr.Metric(label="License Tier", value=enterprise_result.get('license_tier', 'Trial').title())
            gr.Metric(label="Gates Passed", 
                     value=f"{enterprise_result['gates_passed']}/{enterprise_result['total_gates']}")
            gr.Metric(label="Enforcement", 
                     value=enterprise_result.get('enforcement_level', 'advisory').replace('_', ' ').title())
        
        # Gate visualization
        gate_html = "<div style='margin: 15px 0;'>"
        for gate_name, gate_result in enterprise_result.get('gate_results', {}).items():
            status = "βœ…" if gate_result['passed'] else "❌"
            gate_html += f"""
            <div style='background-color: {'#E8F5E9' if gate_result['passed'] else '#FFEBEE'}; 
                        padding: 8px 12px; margin: 5px 0; border-radius: 6px; border-left: 4px solid {'#4CAF50' if gate_result['passed'] else '#F44336'};'>
                <div style='display: flex; justify-content: space-between; align-items: center;'>
                    <span><strong>{gate_name.replace('_', ' ').title()}</strong></span>
                    <span>{status}</span>
                </div>
                <div style='font-size: 12px; color: #666;'>{gate_result['message']}</div>
            </div>
            """
        gate_html += "</div>"
        gr.HTML(gate_html)
        
        # Execution Authority
        authority = enterprise_result['execution_authority']
        authority_color = "#4CAF50" if authority == "GRANTED" else "#F44336"
        gr.HTML(f"""
        <div style='background-color: {authority_color}20; padding: 20px; border-radius: 10px; border: 2px solid {authority_color}; text-align: center; margin: 15px 0;'>
            <h2 style='margin: 0; color: {authority_color};'>{authority}</h2>
            <p style='margin: 5px 0 0 0; font-size: 14px;'>
                {'πŸŽ‰ Autonomous execution permitted' if authority == 'GRANTED' else 'β›” Mechanical enforcement blocked'}
            </p>
        </div>
        """)
        
        # Enterprise Benefits
        with gr.Accordion("πŸš€ Enterprise Benefits", open=True):
            gr.Markdown(f"""
            **Mechanical Enforcement**: {enterprise_result['benefit']}
            
            **Audit Trail**: Logged with ID: {enterprise_result.get('audit_id', 'N/A')}
            
            **License Tier**: {enterprise_result.get('license_tier', 'Trial').title()} with {enterprise_result.get('enforcement_level', 'advisory')} enforcement
            
            **Decision Speed**: {enterprise_result['processing_time']:.3f}s (same as OSS)
            """)

def create_upgrade_panel():
    """Create upgrade comparison and CTA panel"""
    with gr.Column(variant="panel"):
        gr.Markdown("### ⚑ Upgrade to Enterprise")
        
        # Pricing Tiers
        with gr.Row():
            with gr.Column(scale=1, min_width=150):
                gr.Markdown("""
                #### πŸ’° Starter
                **$2,000/mo**
                
                β€’ Human approval gates
                β€’ 10 agents
                β€’ Basic audit
                """)
                gr.Button("Select", variant="secondary", size="sm")
            
            with gr.Column(scale=1, min_width=150):
                gr.Markdown("""
                #### πŸš€ Professional
                **$5,000/mo**
                
                β€’ Autonomous execution
                β€’ 50 agents
                β€’ Advanced gates
                """)
                gr.Button("Select", variant="secondary", size="sm")
            
            with gr.Column(scale=1, min_width=150):
                gr.Markdown("""
                #### 🏒 Enterprise
                **$15,000/mo**
                
                β€’ Full mechanical enforcement
                β€’ 1000+ agents
                β€’ Compliance automation
                """)
                gr.Button("Select", variant="primary", size="sm")
        
        # Trial License Form
        with gr.Accordion("🎁 Get 14-Day Trial License", open=True):
            email_input = gr.Textbox(label="Work Email", placeholder="you@company.com")
            get_trial_btn = gr.Button("Get Trial License", variant="primary")
            trial_output = gr.JSON(label="Your Trial License")
            
            # Link button to function
            demo_app = ARFDemo()
            get_trial_btn.click(
                demo_app.generate_trial_license,
                inputs=[email_input],
                outputs=[trial_output]
            )
        
        # Value Proposition
        gr.Markdown("""
        ---
        ### 🎯 Why Upgrade?
        
        | | OSS | Enterprise |
        |---|---|---|
        | **Enforcement** | Advisory only | Mechanical gates |
        | **Speed** | Human decides | Automated decisions |
        | **Scale** | Manual review | Autonomous at scale |
        | **Compliance** | Self-managed | Built-in audit trail |
        | **Support** | Community | Enterprise SLA |
        
        **Bottom Line**: Reduce operational risk by 92% with mechanical enforcement.
        """)

# Main Demo Interface
def create_demo_interface():
    """Create the main Gradio interface"""
    demo_app = ARFDemo()
    
    with gr.Blocks(
        title="Agentic Reliability Framework (ARF) 3.3.9 Demo",
        theme=gr.themes.Soft(
            primary_hue="blue",
            secondary_hue="orange"
        ),
        css="""
        .gradio-container { max-width: 1200px; margin: 0 auto; }
        .demo-box { border: 1px solid #ddd; border-radius: 10px; padding: 20px; margin: 10px 0; }
        .oss-header { background: linear-gradient(135deg, #1E88E5 0%, #64B5F6 100%); color: white; padding: 15px; border-radius: 10px; }
        .enterprise-header { background: linear-gradient(135deg, #FFB300 0%, #FFD54F 100%); color: white; padding: 15px; border-radius: 10px; }
        """
    ) as demo:
        gr.Markdown("""
        # πŸ€– Agentic Reliability Framework (ARF) 3.3.9
        ### OSS vs Enterprise Capabilities Demo
        
        **Experience the difference**: Open-source advisory vs Enterprise mechanical enforcement
        """)
        
        # Demo Controls
        with gr.Row():
            with gr.Column(scale=3):
                scenario_select = gr.Dropdown(
                    choices=list(demo_app.demo_scenarios.keys()),
                    label="Select Demo Scenario",
                    value="database_drop"
                )
                action_input = gr.Textbox(
                    label="Or Enter Custom Action",
                    placeholder="e.g., DROP DATABASE production, deploy_service v1.2.3, etc.",
                    value="DROP DATABASE production"
                )
                license_input = gr.Textbox(
                    label="Enterprise License Key",
                    placeholder="Enter ARF-TRIAL-XXXXXXX or leave blank for OSS only",
                    value=""
                )
                
                process_btn = gr.Button("πŸš€ Process Action", variant="primary", size="lg")
            
            with gr.Column(scale=1):
                gr.Markdown("""
                ### Quick Actions
                """)
                quick_actions = gr.Radio(
                    choices=["High Risk", "Medium Risk", "Low Risk", "Custom"],
                    label="Risk Level",
                    value="High Risk"
                )
        
        # Results Display
        with gr.Row():
            with gr.Column(scale=1):
                oss_output = gr.JSON(label="ARF OSS Results", visible=False)
                oss_panel = gr.HTML()
            
            with gr.Column(scale=1):
                enterprise_output = gr.JSON(label="ARF Enterprise Results", visible=False)
                enterprise_panel = gr.HTML()
        
        # Comparison Visualization
        with gr.Accordion("πŸ“Š Side-by-Side Comparison", open=True):
            comparison_html = gr.HTML()
        
        # Upgrade Panel
        create_upgrade_panel()
        
        # Processing function
        def process_action(scenario, action, license_key, quick_action):
            """Process action through both OSS and Enterprise"""
            # Use scenario if provided, otherwise use custom action
            if scenario and scenario in demo_app.demo_scenarios:
                effective_action = demo_app.demo_scenarios[scenario]["action"]
            else:
                effective_action = action
            
            # Process through OSS
            oss_result = demo_app.process_action_oss(effective_action, scenario if scenario else None)
            
            # Process through Enterprise if license provided
            enterprise_result = None
            if license_key and license_key.startswith("ARF-"):
                enterprise_result = demo_app.process_action_enterprise(
                    effective_action, license_key, scenario if scenario else None
                )
            else:
                # Show what Enterprise would do with trial
                enterprise_result = {
                    **oss_result,
                    "license_tier": "trial",
                    "enforcement_level": "advisory",
                    "gates_passed": 0,
                    "total_gates": 4,
                    "execution_authority": "REQUIRES UPGRADE",
                    "can_execute_enterprise": False,
                    "benefit": "Upgrade to Enterprise for mechanical enforcement",
                    "gate_results": {}
                }
            
            # Create visual panels
            oss_html = create_oss_panel_html(oss_result)
            enterprise_html = create_enterprise_panel_html(enterprise_result)
            
            # Create comparison visualization
            comparison_data = create_comparison_data(oss_result, enterprise_result)
            
            return oss_result, oss_html, enterprise_result, enterprise_html, comparison_data
        
        # Connect button
        process_btn.click(
            process_action,
            inputs=[scenario_select, action_input, license_input, quick_actions],
            outputs=[oss_output, oss_panel, enterprise_output, enterprise_panel, comparison_html]
        )
        
        # Quick action examples
        def update_quick_action(quick_action):
            examples = {
                "High Risk": "DELETE FROM users WHERE id < 1000",
                "Medium Risk": "ALTER TABLE payments ADD COLUMN metadata JSONB",
                "Low Risk": "SELECT COUNT(*) FROM logs WHERE created_at > NOW() - INTERVAL '1 hour'",
                "Custom": ""
            }
            return examples[quick_action]
        
        quick_actions.change(
            update_quick_action,
            inputs=[quick_actions],
            outputs=[action_input]
        )
        
        # Pre-load first scenario
        demo.load(
            lambda: process_action(
                "database_drop",
                "DROP DATABASE production",
                "",
                "High Risk"
            ),
            outputs=[oss_output, oss_panel, enterprise_output, enterprise_panel, comparison_html]
        )
    
    return demo

# Helper functions for HTML generation
def create_oss_panel_html(result: Dict) -> str:
    """Generate HTML for OSS panel"""
    risk_color = "#E53935" if result['risk_level'] == "High" else "#FFB300" if result['risk_level'] == "Medium" else "#43A047"
    
    return f"""
    <div class="oss-header">
        <h3 style="margin: 0;">πŸ”΅ ARF 3.3.9 OSS (Open Source)</h3>
    </div>
    
    <div style="padding: 20px; background: white; border-radius: 0 0 10px 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
            <div style="text-align: center; padding: 15px; background: #E3F2FD; border-radius: 8px;">
                <div style="font-size: 12px; color: #1E88E5; margin-bottom: 5px;">Reliability Score</div>
                <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{result['reliability_score']:.1%}</div>
            </div>
            
            <div style="text-align: center; padding: 15px; background: #E3F2FD; 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']}</div>
            </div>
            
            <div style="text-align: center; padding: 15px; background: #E3F2FD; border-radius: 8px;">
                <div style="font-size: 12px; color: #1E88E5; margin-bottom: 5px;">Confidence</div>
                <div style="font-size: 24px; font-weight: bold; color: #1E88E5;">{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;">Recommendation</h4>
            </div>
            <p style="margin: 0; font-size: 16px; color: #333;">{result['recommendation']}</p>
            <p style="margin: 5px 0 0 0; font-size: 12px; color: #666;">Processing time: {result['processing_time']:.3f}s</p>
        </div>
        
        <div style="background: #FFF3E0; 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;">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>Policy Violations:</strong> {result['policy_violations']} detected</p>
            <p style="margin: 0; color: #E65100;"><strong>Execution Authority:</strong> {'βœ… Can execute' if result['can_execute_oss'] else '❌ Cannot execute - human decision required'}</p>
        </div>
    </div>
    """

def create_enterprise_panel_html(result: Dict) -> str:
    """Generate HTML for Enterprise panel"""
    license_tier = result.get('license_tier', 'trial').title()
    authority = result.get('execution_authority', 'REQUIRES UPGRADE')
    authority_color = "#4CAF50" if authority == "GRANTED" else "#F44336" if authority == "DENIED" else "#FF9800"
    gates_passed = result.get('gates_passed', 0)
    total_gates = result.get('total_gates', 4)
    
    # Generate gates HTML
    gates_html = ""
    for gate_name, gate_result in result.get('gate_results', {}).items():
        gate_passed = gate_result.get('passed', False)
        gate_color = "#4CAF50" if gate_passed else "#F44336"
        gates_html += f"""
        <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #eee;">
            <span style="margin-right: 10px; font-size: 18px; color: {gate_color};">{'βœ…' if gate_passed else '❌'}</span>
            <div style="flex: 1;">
                <div style="font-weight: 500;">{gate_name.replace('_', ' ').title()}</div>
                <div style="font-size: 12px; color: #666;">{gate_result.get('message', '')}</div>
            </div>
        </div>
        """
    
    return f"""
    <div class="enterprise-header">
        <h3 style="margin: 0;">🟑 ARF 3.3.9 Enterprise ({license_tier})</h3>
    </div>
    
    <div style="padding: 20px; background: white; border-radius: 0 0 10px 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
            <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
                <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">License Tier</div>
                <div style="font-size: 20px; font-weight: bold; color: #FF8F00;">{license_tier}</div>
            </div>
            
            <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
                <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">Gates Passed</div>
                <div style="font-size: 24px; font-weight: bold; color: #FF8F00;">{gates_passed}/{total_gates}</div>
            </div>
            
            <div style="text-align: center; padding: 15px; background: #FFF8E1; border-radius: 8px;">
                <div style="font-size: 12px; color: #FF8F00; margin-bottom: 5px;">Enforcement</div>
                <div style="font-size: 14px; font-weight: bold; color: #FF8F00;">{result.get('enforcement_level', 'advisory').replace('_', ' ').title()}</div>
            </div>
        </div>
        
        <div style="margin-bottom: 20px;">
            <h4 style="margin-bottom: 10px; color: #FF8F00;">Mechanical Gates</h4>
            <div style="background: #FFFDE7; padding: 15px; border-radius: 8px;">
                {gates_html if gates_html else "<p style='color: #666; text-align: center;'>No gate data available</p>"}
            </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: 28px; font-weight: bold; color: {authority_color}; margin-bottom: 5px;">{authority}</div>
            <div style="color: {authority_color};">
                {'πŸŽ‰ Autonomous execution permitted' if authority == 'GRANTED' else 'β›” Mechanical enforcement blocked' if authority == 'DENIED' else '⬆️ Upgrade required for enforcement'}
            </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;">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> {result.get('audit_id', 'Available with license')}</p>
            <p style="margin: 0; color: #2E7D32;"><strong>Decision Speed:</strong> {result.get('processing_time', 0):.3f}s (same as OSS)</p>
        </div>
    </div>
    """

def create_comparison_data(oss_result: Dict, enterprise_result: Dict) -> str:
    """Create comparison visualization HTML"""
    # Calculate key metrics
    oss_can_execute = oss_result.get('can_execute_oss', False)
    enterprise_can_execute = enterprise_result.get('can_execute_enterprise', False)
    gates_passed = enterprise_result.get('gates_passed', 0)
    total_gates = enterprise_result.get('total_gates', 4)
    
    return f"""
    <div style="padding: 20px; background: white; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h3 style="margin-top: 0; text-align: center;">πŸ“Š Side-by-Side Comparison</h3>
        
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <!-- OSS Column -->
            <div style="text-align: center;">
                <h4 style="color: #1E88E5;">πŸ”΅ OSS 3.3.9</h4>
                <div style="margin: 15px 0;">
                    <div style="font-size: 48px; color: #1E88E5; margin-bottom: 5px;">{'⚠️' 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="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    <strong>Human Decision Required</strong>
                </div>
                <div style="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    Risk: {oss_result.get('risk_level', 'Unknown')}
                </div>
                <div style="background: #E3F2FD; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    {oss_result.get('policy_violations', 0)} Policy Violations
                </div>
            </div>
            
            <!-- Enterprise Column -->
            <div style="text-align: center;">
                <h4 style="color: #FFB300;">🟑 Enterprise</h4>
                <div style="margin: 15px 0;">
                    <div style="font-size: 48px; color: #FFB300; margin-bottom: 5px;">
                        {'β›”' if not enterprise_can_execute else 'βœ…'}
                    </div>
                    <div style="font-size: 18px; font-weight: bold; color: {'#F44336' if not enterprise_can_execute else '#43A047'}">
                        {enterprise_result.get('execution_authority', 'REQUIRES UPGRADE')}
                    </div>
                </div>
                <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    <strong>Mechanical Enforcement</strong>
                </div>
                <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    {gates_passed}/{total_gates} Gates Passed
                </div>
                <div style="background: #FFF8E1; padding: 10px; border-radius: 6px; margin: 5px 0;">
                    License: {enterprise_result.get('license_tier', 'trial').title()}
                </div>
            </div>
        </div>
        
        <!-- Value Proposition -->
        <div style="margin-top: 20px; padding: 15px; background: linear-gradient(135deg, #FFB30020 0%, #1E88E520 100%); border-radius: 8px;">
            <h4 style="text-align: center; margin-top: 0;">🎯 Upgrade Value Proposition</h4>
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                <div style="text-align: center; padding: 10px;">
                    <div style="font-size: 12px; color: #666;">Risk Reduction</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">92%</div>
                </div>
                <div style="text-align: center; padding: 10px;">
                    <div style="font-size: 12px; color: #666;">Decision Speed</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">100x</div>
                </div>
                <div style="text-align: center; padding: 10px;">
                    <div style="font-size: 12px; color: #666;">False Positives</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">-85%</div>
                </div>
                <div style="text-align: center; padding: 10px;">
                    <div style="font-size: 12px; color: #666;">Operational Cost</div>
                    <div style="font-size: 20px; font-weight: bold; color: #43A047;">-75%</div>
                </div>
            </div>
        </div>
    </div>
    """

# Launch the demo
if __name__ == "__main__":
    demo = create_demo_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True,
        debug=True
    )