File size: 29,263 Bytes
65776b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Enhanced Psychology Layer with Prospect Theory Mathematics
PhD-Level Psychological Optimization for Investor Demos
"""

import random
import numpy as np
from typing import Dict, List, Tuple, Any
from dataclasses import dataclass
from enum import Enum

class PsychologicalPrinciple(Enum):
    """Psychological principles with mathematical implementations"""
    LOSS_AVERSION = "loss_aversion"
    PROSPECT_THEORY = "prospect_theory"
    SOCIAL_PROOF = "social_proof"
    SCARCITY = "scarcity"
    AUTHORITY = "authority"
    ANCHORING = "anchoring"

@dataclass
class ProspectTheoryParameters:
    """Kahneman & Tversky's Prospect Theory parameters"""
    alpha: float = 0.88      # Risk aversion for gains (0 ≀ Ξ± ≀ 1)
    beta: float = 0.88       # Risk seeking for losses (0 ≀ Ξ² ≀ 1)
    lambda_param: float = 2.25  # Loss aversion coefficient (Ξ» > 1)
    gamma: float = 0.61      # Probability weighting for gains
    delta: float = 0.69      # Probability weighting for losses
    
    def __post_init__(self):
        """Validate parameters"""
        assert 0 < self.alpha <= 1, "Alpha must be between 0 and 1"
        assert 0 < self.beta <= 1, "Beta must be between 0 and 1"
        assert self.lambda_param > 1, "Lambda must be greater than 1"
        assert 0 < self.gamma <= 1, "Gamma must be between 0 and 1"
        assert 0 < self.delta <= 1, "Delta must be between 0 and 1"

class ProspectTheoryEngine:
    """Mathematical implementation of Kahneman & Tversky's Prospect Theory"""
    
    def __init__(self, params: ProspectTheoryParameters = None):
        self.params = params or ProspectTheoryParameters()
        
    def value_function(self, x: float) -> float:
        """
        Kahneman & Tversky's value function:
        v(x) = { x^Ξ± if x β‰₯ 0, -Ξ»(-x)^Ξ² if x < 0 }
        
        For risk scores (always positive loss domain):
        perceived_loss = risk_score^Ξ± * Ξ»
        """
        if x >= 0:
            # Gains domain (not typically used for risk)
            return x ** self.params.alpha
        else:
            # Loss domain (risk is always positive loss)
            return -self.params.lambda_param * ((-x) ** self.params.beta)
    
    def probability_weighting(self, p: float, is_gain: bool = False) -> float:
        """
        Probability weighting function Ο€(p)
        Overweights small probabilities, underweights large probabilities
        
        Ο€(p) = p^Ξ³ / (p^Ξ³ + (1-p)^Ξ³)^(1/Ξ³) for gains
        Ο€(p) = p^Ξ΄ / (p^Ξ΄ + (1-p)^Ξ΄)^(1/Ξ΄) for losses
        """
        if p == 0:
            return 0
        if p == 1:
            return 1
        
        gamma = self.params.gamma if is_gain else self.params.delta
        
        numerator = p ** gamma
        denominator = (p ** gamma + (1 - p) ** gamma) ** (1 / gamma)
        
        return numerator / denominator
    
    def weighted_perceived_risk(self, risk_score: float) -> float:
        """
        Calculate prospect-theory weighted perceived risk
        Combines value function with probability weighting
        """
        # Loss domain (risk is always positive loss)
        base_value = self.value_function(-risk_score)  # Negative because it's a loss
        
        # Probability weighting for losses
        weighted_prob = self.probability_weighting(risk_score, is_gain=False)
        
        # Combine
        perceived_risk = abs(base_value) * weighted_prob
        
        return min(1.0, perceived_risk)
    
    def calculate_psychological_impact(self, risk_score: float, license_tier: str) -> Dict[str, Any]:
        """
        Multi-dimensional psychological impact calculation
        Based on Prospect Theory with tier-specific adjustments
        """
        # Base perceived risk using Prospect Theory
        perceived_risk = self.weighted_perceived_risk(risk_score)
        
        # License-tier anxiety multiplier (enterprise reduces anxiety)
        anxiety_multipliers = {
            'oss': 1.3,      # Higher anxiety without protection
            'trial': 1.0,    # Balanced with temporary protection
            'starter': 0.9,  # Some protection
            'professional': 0.8, # Good protection
            'enterprise': 0.7  # Full protection
        }
        
        final_anxiety = perceived_risk * anxiety_multipliers.get(license_tier, 1.0)
        
        # Conversion probability based on anxiety and tier (sigmoid function)
        # Higher anxiety β†’ higher conversion probability up to a point
        conversion_probability = self._sigmoid_conversion(final_anxiety, license_tier)
        
        # Urgency score (derivative of anxiety)
        urgency_score = min(1.0, final_anxiety * 1.2)
        
        # Loss aversion weight (tier-specific)
        loss_aversion_weight = self.params.lambda_param * (1 + (license_tier == 'oss') * 0.5)
        
        return {
            'perceived_risk': round(perceived_risk, 3),
            'anxiety_level': round(final_anxiety, 3),
            'conversion_probability': round(conversion_probability, 3),
            'urgency_score': round(urgency_score, 3),
            'loss_aversion_weight': round(loss_aversion_weight, 2),
            'psychological_impact_category': self._categorize_impact(final_anxiety),
            'prospect_theory_parameters': {
                'alpha': self.params.alpha,
                'beta': self.params.beta,
                'lambda': self.params.lambda_param,
                'gamma': self.params.gamma,
                'delta': self.params.delta
            }
        }
    
    def _sigmoid_conversion(self, anxiety: float, license_tier: str) -> float:
        """Sigmoid function for conversion probability"""
        # Base conversion curve
        x = (anxiety - 0.5) * 3  # Center at 0.5 anxiety, scale by 3
        
        # Sigmoid with tier-specific adjustments
        base_sigmoid = 1 / (1 + np.exp(-x))
        
        # Tier multipliers (enterprise users convert more easily)
        tier_multipliers = {
            'oss': 0.6,
            'trial': 0.8,
            'starter': 0.85,
            'professional': 0.9,
            'enterprise': 0.95
        }
        
        multiplier = tier_multipliers.get(license_tier, 0.8)
        converted = base_sigmoid * multiplier
        
        # Add minimum conversion probability
        return min(0.95, max(0.1, converted))
    
    def _categorize_impact(self, anxiety: float) -> str:
        """Categorize psychological impact"""
        if anxiety > 0.8:
            return "CRITICAL_IMPACT"
        elif anxiety > 0.6:
            return "HIGH_IMPACT"
        elif anxiety > 0.4:
            return "MODERATE_IMPACT"
        elif anxiety > 0.2:
            return "LOW_IMPACT"
        else:
            return "MINIMAL_IMPACT"

class BayesianSocialProofEngine:
    """Bayesian social proof optimization with credibility updating"""
    
    def __init__(self):
        # Beta distribution priors for different proof types
        # Ξ± = successes + 1, Ξ² = failures + 1
        self.priors = {
            'fortune_500': (9, 2),    # Ξ±=9, Ξ²=2 β†’ 82% prior credibility
            'scaleup': (7, 4),        # Ξ±=7, Ξ²=4 β†’ 64% prior credibility
            'developer_count': (8, 3), # Ξ±=8, Ξ²=3 β†’ 73% prior credibility
            'savings': (10, 1),       # Ξ±=10, Ξ²=1 β†’ 91% prior credibility
            'incident_reduction': (9, 2), # 82% prior credibility
            'compliance': (8, 2),     # 80% prior credibility
        }
        
        # User type profiles with likelihood weights
        self.user_profiles = {
            'engineer': {
                'fortune_500': 0.6,
                'scaleup': 0.8,
                'developer_count': 0.9,
                'savings': 0.7,
                'incident_reduction': 0.95,
                'compliance': 0.5
            },
            'executive': {
                'fortune_500': 0.9,
                'savings': 0.95,
                'scaleup': 0.7,
                'incident_reduction': 0.85,
                'compliance': 0.9,
                'developer_count': 0.4
            },
            'investor': {
                'savings': 0.9,
                'fortune_500': 0.85,
                'growth': 0.8,
                'incident_reduction': 0.75,
                'compliance': 0.7,
                'scaleup': 0.6
            },
            'compliance_officer': {
                'compliance': 0.95,
                'fortune_500': 0.8,
                'incident_reduction': 0.85,
                'savings': 0.6,
                'developer_count': 0.3,
                'scaleup': 0.4
            }
        }
        
        # Proof templates
        self.proof_templates = {
            'fortune_500': {
                'title': '🏒 Trusted by Fortune 500',
                'message': 'Deployed at 50+ Fortune 500 companies including FAANG',
                'icon': '🏒',
                'credibility_baseline': 0.85
            },
            'scaleup': {
                'title': 'πŸš€ Scale-up Proven',
                'message': 'Trusted by 200+ high-growth tech scale-ups',
                'icon': 'πŸš€',
                'credibility_baseline': 0.75
            },
            'developer_count': {
                'title': 'πŸ‘¨β€πŸ’» Developer Love',
                'message': 'Join 1,000+ active developers using ARF for AI safety',
                'icon': 'πŸ‘¨β€πŸ’»',
                'credibility_baseline': 0.8
            },
            'savings': {
                'title': 'πŸ’° Proven Savings',
                'message': 'Average $3.9M breach cost prevented, 92% incident reduction',
                'icon': 'πŸ’°',
                'credibility_baseline': 0.9
            },
            'incident_reduction': {
                'title': 'πŸ›‘οΈ Risk Reduction',
                'message': '92% of incidents prevented with mechanical gates',
                'icon': 'πŸ›‘οΈ',
                'credibility_baseline': 0.88
            },
            'compliance': {
                'title': 'πŸ“‹ Compliance Ready',
                'message': 'SOC 2, GDPR, ISO 27001 certified with zero findings',
                'icon': 'πŸ“‹',
                'credibility_baseline': 0.82
            }
        }
    
    def get_optimized_proof(self, user_type: str, license_tier: str, 
                          risk_context: Dict[str, Any]) -> Dict[str, Any]:
        """
        Get psychologically optimized social proof using Bayesian updating
        """
        user_type = user_type if user_type in self.user_profiles else 'engineer'
        user_profile = self.user_profiles[user_type]
        
        # Calculate posterior credibility for each proof type
        posteriors = {}
        for proof_type, (alpha_prior, beta_prior) in self.priors.items():
            if proof_type not in user_profile:
                continue
            
            likelihood = user_profile[proof_type]
            
            # Bayesian update: Posterior = Beta(Ξ± + successes, Ξ² + failures)
            # successes = likelihood * 10, failures = (1 - likelihood) * 10
            successes = likelihood * 10
            failures = (1 - likelihood) * 10
            
            posterior_alpha = alpha_prior + successes
            posterior_beta = beta_prior + failures
            
            posterior_mean = posterior_alpha / (posterior_alpha + posterior_beta)
            posterior_variance = (posterior_alpha * posterior_beta) / \
                               ((posterior_alpha + posterior_beta) ** 2 * \
                                (posterior_alpha + posterior_beta + 1))
            
            posteriors[proof_type] = {
                'credibility': posterior_mean,
                'confidence': 1 - posterior_variance,
                'alpha': posterior_alpha,
                'beta': posterior_beta,
                'likelihood': likelihood
            }
        
        if not posteriors:
            return self._get_default_proof(license_tier)
        
        # Select proof with highest credibility
        best_proof_type = max(posteriors.items(), key=lambda x: x[1]['credibility'])[0]
        best_proof_data = posteriors[best_proof_type]
        
        return self._format_proof(
            best_proof_type, 
            best_proof_data, 
            user_type, 
            license_tier, 
            risk_context
        )
    
    def _format_proof(self, proof_type: str, proof_data: Dict[str, Any],
                     user_type: str, license_tier: str, 
                     risk_context: Dict[str, Any]) -> Dict[str, Any]:
        """Format social proof with credibility metrics"""
        template = self.proof_templates.get(
            proof_type, 
            self.proof_templates['developer_count']
        )
        
        # Adjust message based on license tier
        tier_adjustments = {
            'trial': "Start your free trial today",
            'starter': "Upgrade to Starter for mechanical gates",
            'professional': "Professional includes 24/7 support",
            'enterprise': "Enterprise includes dedicated support"
        }
        
        adjusted_message = f"{template['message']}. {tier_adjustments.get(license_tier, '')}"
        
        return {
            **template,
            'message': adjusted_message,
            'proof_type': proof_type,
            'credibility': round(proof_data['credibility'], 3),
            'confidence': round(proof_data['confidence'], 3),
            'credibility_interval': self._calculate_credibility_interval(
                proof_data['alpha'], proof_data['beta']
            ),
            'optimized_for': user_type,
            'recommended_for_tier': license_tier,
            'risk_context_match': self._assess_risk_context_match(proof_type, risk_context),
            'bayesian_parameters': {
                'prior_alpha': self.priors[proof_type][0],
                'prior_beta': self.priors[proof_type][1],
                'posterior_alpha': proof_data['alpha'],
                'posterior_beta': proof_data['beta'],
                'likelihood': proof_data['likelihood']
            }
        }
    
    def _calculate_credibility_interval(self, alpha: float, beta: float, 
                                       confidence: float = 0.95) -> Tuple[float, float]:
        """Calculate credibility interval for Beta distribution"""
        # Simplified calculation for demo
        mean = alpha / (alpha + beta)
        variance = (alpha * beta) / ((alpha + beta) ** 2 * (alpha + beta + 1))
        std_dev = np.sqrt(variance)
        
        # Approximate 95% interval
        lower = max(0, mean - 1.96 * std_dev)
        upper = min(1, mean + 1.96 * std_dev)
        
        return round(lower, 3), round(upper, 3)
    
    def _assess_risk_context_match(self, proof_type: str, risk_context: Dict[str, Any]) -> float:
        """Assess how well proof matches risk context"""
        risk_score = risk_context.get('risk_score', 0.5)
        risk_category = risk_context.get('risk_category', 'MEDIUM')
        
        # Proof effectiveness by risk level
        effectiveness = {
            'fortune_500': {'LOW': 0.7, 'MEDIUM': 0.8, 'HIGH': 0.9, 'CRITICAL': 0.95},
            'savings': {'LOW': 0.6, 'MEDIUM': 0.8, 'HIGH': 0.9, 'CRITICAL': 0.95},
            'incident_reduction': {'LOW': 0.5, 'MEDIUM': 0.7, 'HIGH': 0.85, 'CRITICAL': 0.9},
            'compliance': {'LOW': 0.6, 'MEDIUM': 0.7, 'HIGH': 0.8, 'CRITICAL': 0.85},
            'developer_count': {'LOW': 0.8, 'MEDIUM': 0.7, 'HIGH': 0.6, 'CRITICAL': 0.5},
            'scaleup': {'LOW': 0.7, 'MEDIUM': 0.75, 'HIGH': 0.8, 'CRITICAL': 0.7}
        }
        
        return effectiveness.get(proof_type, {}).get(risk_category, 0.7)
    
    def _get_default_proof(self, license_tier: str) -> Dict[str, Any]:
        """Get default social proof"""
        return {
            'title': 'πŸ‘¨β€πŸ’» Developer Trusted',
            'message': 'Join 1,000+ developers using ARF for AI safety',
            'icon': 'πŸ‘¨β€πŸ’»',
            'credibility': 0.8,
            'confidence': 0.7,
            'proof_type': 'default',
            'optimized_for': 'default',
            'recommended_for_tier': license_tier,
            'risk_context_match': 0.7,
            'credibility_interval': (0.72, 0.88)
        }

class EnhancedPsychologyEngine:
    """Complete psychology engine combining all principles"""
    
    def __init__(self):
        self.prospect_theory = ProspectTheoryEngine()
        self.social_proof = BayesianSocialProofEngine()
        
        # Loss aversion scenarios with financial impact
        self.loss_scenarios = {
            "CRITICAL": [
                {"text": "Data breach ($3.9M average cost)", "impact": 3900000},
                {"text": "Service disruption ($300k/hour)", "impact": 7200000},
                {"text": "Compliance fines (up to $20M)", "impact": 20000000},
                {"text": "Reputational damage (6+ months recovery)", "impact": 5000000}
            ],
            "HIGH": [
                {"text": "Data corruption (24h recovery)", "impact": 1000000},
                {"text": "Performance degradation (50% slower)", "impact": 500000},
                {"text": "Security vulnerability exposure", "impact": 750000},
                {"text": "Customer churn (15% increase)", "impact": 1500000}
            ],
            "MEDIUM": [
                {"text": "Increased operational overhead", "impact": 250000},
                {"text": "Manual review delays (2+ hours)", "impact": 150000},
                {"text": "Team productivity loss (20%)", "impact": 300000},
                {"text": "Audit findings & remediation", "impact": 200000}
            ],
            "LOW": [
                {"text": "Minor configuration drift", "impact": 50000},
                {"text": "Documentation gaps", "impact": 25000},
                {"text": "Process inefficiencies", "impact": 75000},
                {"text": "Training requirements", "impact": 100000}
            ]
        }
        
        # Scarcity messaging with mathematical decay
        self.scarcity_patterns = {
            "trial": {
                "base_urgency": 0.8,
                "decay_rate": 0.07,  # per day
                "messages": [
                    "⏳ {days} days remaining in free trial",
                    "🎁 Trial ends in {days} days - upgrade to keep mechanical gates",
                    "⚠️ Free access expires in {days} days"
                ]
            },
            "starter": {
                "base_urgency": 0.6,
                "decay_rate": 0.05,
                "messages": [
                    "πŸ’° Special pricing ends in {days} days",
                    "πŸ‘₯ Limited seats at current price",
                    "⏰ Quarterly offer expires soon"
                ]
            }
        }
        
        # Authority signals with credibility scores
        self.authority_signals = [
            {"text": "SOC 2 Type II Certified", "credibility": 0.95, "audience": ["executive", "compliance"]},
            {"text": "GDPR & CCPA Compliant", "credibility": 0.9, "audience": ["compliance", "executive"]},
            {"text": "ISO 27001 Certified", "credibility": 0.92, "audience": ["executive", "compliance"]},
            {"text": "99.9% SLA Guarantee", "credibility": 0.88, "audience": ["engineer", "executive"]},
            {"text": "24/7 Dedicated Support", "credibility": 0.85, "audience": ["engineer", "executive"]},
            {"text": "On-prem Deployment Available", "credibility": 0.87, "audience": ["executive", "compliance"]},
            {"text": "Fortune 500 Deployed", "credibility": 0.93, "audience": ["executive", "investor"]},
            {"text": "Venture Backed", "credibility": 0.8, "audience": ["investor", "executive"]}
        ]
    
    def generate_comprehensive_insights(self, risk_score: float, risk_category: str,
                                       license_tier: str, user_type: str = "engineer",
                                       days_remaining: int = 14) -> Dict[str, Any]:
        """
        Generate comprehensive psychological insights for investor demos
        """
        # Prospect Theory impact
        prospect_impact = self.prospect_theory.calculate_psychological_impact(
            risk_score, license_tier
        )
        
        # Social proof optimization
        social_proof = self.social_proof.get_optimized_proof(
            user_type, license_tier, 
            {"risk_score": risk_score, "risk_category": risk_category}
        )
        
        # Loss aversion framing
        loss_aversion = self._generate_loss_aversion_framing(risk_category, risk_score)
        
        # Scarcity messaging
        scarcity = self._generate_scarcity_message(license_tier, days_remaining)
        
        # Authority signals
        authority = self._generate_authority_signals(user_type)
        
        # Anchoring effect (reference pricing)
        anchoring = self._generate_anchoring_effect(license_tier)
        
        # Conversion prediction
        conversion_prediction = self._predict_conversion(
            prospect_impact['anxiety_level'],
            social_proof['credibility'],
            scarcity.get('urgency', 0.5),
            license_tier
        )
        
        return {
            "prospect_theory_impact": prospect_impact,
            "optimized_social_proof": social_proof,
            "loss_aversion_framing": loss_aversion,
            "scarcity_signaling": scarcity,
            "authority_signals": authority,
            "anchoring_effects": anchoring,
            "conversion_prediction": conversion_prediction,
            "psychological_summary": self._generate_psychological_summary(
                prospect_impact, social_proof, loss_aversion
            ),
            "user_type": user_type,
            "license_tier": license_tier,
            "risk_context": {
                "score": risk_score,
                "category": risk_category,
                "perceived_impact": prospect_impact['perceived_risk']
            }
        }
    
    def _generate_loss_aversion_framing(self, risk_category: str, risk_score: float) -> Dict[str, Any]:
        """Generate loss aversion framing with financial impact"""
        scenarios = self.loss_scenarios.get(risk_category, self.loss_scenarios["MEDIUM"])
        
        # Select scenarios based on risk score
        num_scenarios = min(3, int(risk_score * 4) + 1)
        selected = random.sample(scenarios, min(num_scenarios, len(scenarios)))
        
        # Calculate total potential impact
        total_impact = sum(s["impact"] for s in selected)
        
        return {
            "title": f"🚨 Without Enterprise protection, you risk:",
            "scenarios": [s["text"] for s in selected],
            "total_potential_impact": f"${total_impact:,.0f}",
            "average_scenario_impact": f"${total_impact/len(selected):,.0f}",
            "risk_category": risk_category,
            "psychological_impact": "HIGH" if risk_category in ["CRITICAL", "HIGH"] else "MODERATE"
        }
    
    def _generate_scarcity_message(self, license_tier: str, days_remaining: int) -> Dict[str, Any]:
        """Generate scarcity messaging with mathematical urgency"""
        if license_tier not in self.scarcity_patterns:
            return {"message": "", "urgency": 0.0}
        
        pattern = self.scarcity_patterns[license_tier]
        
        # Calculate urgency with decay
        urgency = pattern["base_urgency"] * (1 - pattern["decay_rate"] * (14 - days_remaining))
        urgency = max(0.1, min(0.95, urgency))
        
        # Select message
        message_template = random.choice(pattern["messages"])
        message = message_template.format(days=days_remaining)
        
        return {
            "message": message,
            "urgency": round(urgency, 2),
            "days_remaining": days_remaining,
            "urgency_category": "HIGH" if urgency > 0.7 else "MEDIUM" if urgency > 0.4 else "LOW"
        }
    
    def _generate_authority_signals(self, user_type: str, count: int = 3) -> List[Dict[str, Any]]:
        """Generate authority signals optimized for user type"""
        # Filter signals for user type
        relevant_signals = [
            s for s in self.authority_signals 
            if user_type in s["audience"]
        ]
        
        # Sort by credibility
        relevant_signals.sort(key=lambda x: x["credibility"], reverse=True)
        
        # Select top signals
        selected = relevant_signals[:count]
        
        return [
            {
                "text": s["text"],
                "credibility": s["credibility"],
                "relevance_to_user": "HIGH" if user_type in s["audience"] else "MEDIUM",
                "formatted": f"βœ“ {s['text']} ({s['credibility']:.0%} credibility)"
            }
            for s in selected
        ]
    
    def _generate_anchoring_effect(self, current_tier: str) -> Dict[str, Any]:
        """Generate anchoring effects for pricing"""
        tier_prices = {
            "oss": 0,
            "trial": 0,
            "starter": 2000,
            "professional": 5000,
            "enterprise": 15000
        }
        
        current_price = tier_prices.get(current_tier, 0)
        
        # Generate reference prices (anchors)
        anchors = []
        for tier, price in tier_prices.items():
            if price > current_price:
                discount = ((price - current_price) / price) * 100
                anchors.append({
                    "reference_tier": tier,
                    "reference_price": price,
                    "discount_percentage": round(discount, 1),
                    "anchor_strength": "STRONG" if discount > 50 else "MODERATE"
                })
        
        # Select strongest anchor
        if anchors:
            strongest_anchor = max(anchors, key=lambda x: x["discount_percentage"])
        else:
            strongest_anchor = {
                "reference_tier": "enterprise",
                "reference_price": 15000,
                "discount_percentage": 100.0,
                "anchor_strength": "MAXIMUM"
            }
        
        return {
            "current_tier": current_tier,
            "current_price": current_price,
            "anchors": anchors,
            "strongest_anchor": strongest_anchor,
            "perceived_value": f"{strongest_anchor['discount_percentage']:.0f}% discount vs {strongest_anchor['reference_tier']}",
            "anchoring_effect_strength": strongest_anchor["anchor_strength"]
        }
    
    def _predict_conversion(self, anxiety: float, social_credibility: float,
                           scarcity_urgency: float, license_tier: str) -> Dict[str, Any]:
        """Predict conversion probability using multiple factors"""
        # Base conversion probability
        base_prob = anxiety * 0.6 + social_credibility * 0.3 + scarcity_urgency * 0.1
        
        # Tier adjustment
        tier_multipliers = {
            'oss': 1.0,
            'trial': 1.2,
            'starter': 1.1,
            'professional': 1.0,
            'enterprise': 0.8
        }
        
        adjusted_prob = base_prob * tier_multipliers.get(license_tier, 1.0)
        adjusted_prob = min(0.95, max(0.05, adjusted_prob))
        
        # Confidence interval
        std_error = np.sqrt(adjusted_prob * (1 - adjusted_prob) / 100)  # Assuming 100 samples
        ci_lower = max(0, adjusted_prob - 1.96 * std_error)
        ci_upper = min(1, adjusted_prob + 1.96 * std_error)
        
        return {
            "conversion_probability": round(adjusted_prob, 3),
            "confidence_interval": (round(ci_lower, 3), round(ci_upper, 3)),
            "confidence_width": round(ci_upper - ci_lower, 3),
            "key_factors": {
                "anxiety_contribution": round(anxiety * 0.6, 3),
                "social_proof_contribution": round(social_credibility * 0.3, 3),
                "scarcity_contribution": round(scarcity_urgency * 0.1, 3)
            },
            "prediction_quality": "HIGH" if (ci_upper - ci_lower) < 0.2 else "MODERATE"
        }
    
    def _generate_psychological_summary(self, prospect_impact: Dict,
                                       social_proof: Dict, loss_aversion: Dict) -> str:
        """Generate psychological summary for investors"""
        anxiety = prospect_impact.get('anxiety_level', 0.5)
        credibility = social_proof.get('credibility', 0.7)
        
        if anxiety > 0.7 and credibility > 0.8:
            return "HIGH CONVERSION POTENTIAL: Strong anxiety combined with credible social proof creates ideal conversion conditions."
        elif anxiety > 0.5:
            return "GOOD CONVERSION POTENTIAL: Moderate anxiety levels with supporting social proof suggest healthy conversion rates."
        elif credibility > 0.85:
            return "STRONG SOCIAL PROOF: High credibility signals will drive conversions even with lower anxiety levels."
        else:
            return "BASIC CONVERSION SETUP: Standard psychological triggers in place. Consider increasing urgency or social proof."