#!/usr/bin/env python3
"""
World Model Integration v3 - With Comprehensive Domain Knowledge
Added: Software Engineering, Strategic Planning, Risk Management
"""
import sys
sys.path.insert(0, '/Eden/CAPABILITIES')
from eden_metacap_WORLD_MODEL import DeepWorldModel
from eden_metacap_MEMORY_CORE import MemoryCore

PHI = 1.618033988749895

class ComprehensiveWorldModel(DeepWorldModel):
    """World model with software engineering and strategic planning knowledge"""
    
    def __init__(self):
        super().__init__()
        
        # Eden-specific knowledge (from v2)
        self.eden_knowledge = {
            'capability_generation': {
                'past_issue': 'Generated 64,550 files uncontrollably',
                'consequence': 'System became bloated and slow',
                'lesson': 'Quality over quantity - controlled generation only'
            },
            'system_optimization': {
                'recent_success': 'Reduced from 64,550 to 416 files',
                'result': '96% reduction, 25x faster',
                'lesson': 'Consolidation works - maintain lean state'
            }
        }
        
        # Software Engineering Best Practices
        self.software_engineering = {
            'testing': {
                'principle': 'Test before deploying to production',
                'risk_levels': {
                    'no_testing': 'critical - can break entire system',
                    'sandbox_testing': 'low - safe isolated environment',
                    'production_testing': 'high - users affected by bugs'
                },
                'best_practice': 'Always test in sandbox first, then gradual rollout'
            },
            'optimization': {
                'rule': 'Measure before optimizing, test after optimizing',
                'safe_approach': [
                    'Benchmark current performance',
                    'Test optimization in sandbox',
                    'Validate improvements',
                    'Deploy with monitoring',
                    'Rollback plan ready'
                ],
                'unsafe_approach': 'Implement immediately without testing',
                'lesson': '30% speedup means nothing if it breaks the system'
            },
            'memory_management': {
                'good_size': 'Under 500MB for small systems',
                'action_threshold': 'Over 1GB requires attention',
                'best_practice': 'Scheduled compression during idle',
                'avoid': 'Deleting all old data (lose learning)',
                'balance': 'Compress old low-importance, keep valuable memories'
            },
            'code_quality': {
                'priority_order': [
                    '1. Correctness (does it work?)',
                    '2. Safety (can it break things?)',
                    '3. Performance (is it fast enough?)',
                    '4. Optimization (can we make it faster?)'
                ],
                'lesson': 'Working > Fast. Safe > Optimal.'
            }
        }
        
        # Strategic Planning Knowledge
        self.strategic_planning = {
            'product_vs_research': {
                'principle': 'Focus compounds, distraction dilutes',
                'scenarios': {
                    'creator_busy': 'Eden focuses on AGI research (her expertise)',
                    'creator_available': 'Creator handles product, Eden supports',
                    'balanced': 'Delegate product tasks to specialized capabilities',
                    'wrong': 'Try to do everything at once (nothing gets done well)'
                },
                'lesson': 'Play to strengths - Eden = AGI research, Creator = product/market'
            },
            'resource_allocation': {
                'rule': 'Protect core functionality before adding features',
                'priorities': [
                    '1. System stability (must work)',
                    '2. Core capabilities (must be available)',
                    '3. Optimizations (nice to have)',
                    '4. New features (future value)'
                ],
                'lesson': 'Stable simple system > unstable complex system'
            },
            'decision_making': {
                'framework': 'Reversible vs Irreversible decisions',
                'reversible': 'Can test, try, undo - be aggressive',
                'irreversible': 'Permanent impact - be cautious',
                'examples': {
                    'reversible': ['compress memories (can restore backup)', 'test optimization (can rollback)'],
                    'irreversible': ['delete all data', 'deploy without backup']
                }
            },
            'timing': {
                'principle': 'Do the right thing at the right time',
                'immediate': ['Critical bugs', 'Security issues', 'System failures'],
                'scheduled': ['Optimizations', 'Compression', 'Maintenance'],
                'future': ['New features', 'Major refactors', 'Platform changes'],
                'lesson': 'Urgency ≠ Importance. Schedule wisely.'
            }
        }
        
        # Risk Management
        self.risk_management = {
            'assessment': {
                'critical': 'Could break entire system or lose data',
                'high': 'Could cause significant problems',
                'medium': 'Might cause minor issues',
                'low': 'Safe with standard precautions',
                'very_low': 'Almost no risk'
            },
            'mitigation': {
                'critical_risk': ['Don\'t do it', 'Or extensive testing + backup + rollback plan'],
                'high_risk': ['Sandbox test', 'Backup first', 'Monitor closely'],
                'medium_risk': ['Standard testing', 'Have rollback plan'],
                'low_risk': ['Basic validation', 'Can proceed'],
                'very_low_risk': ['Proceed with confidence']
            }
        }
    
    def predict_outcome(self, action: str, context: dict) -> dict:
        """Enhanced prediction with comprehensive domain knowledge"""
        
        # Get base prediction
        base_prediction = super().predict_outcome(action, context)
        
        action_lower = action.lower()
        consequences = []
        confidence = 0.5
        risk_level = 'medium'
        
        # ===== EDEN-SPECIFIC DECISIONS =====
        if any(pattern in action_lower for pattern in ['generate 100', 'generate many', 'generate.*immediately']):
            consequences.append("🚫 CRITICAL: Repeats the 64K file mistake")
            consequences.append("Would undo optimization work")
            confidence = 0.95
            risk_level = 'critical'
        
        elif 'consolidate' in action_lower or ('do nothing' in action_lower and context.get('system_health') == 'excellent'):
            consequences.append("✅ Maintains optimized state")
            consequences.append("No unnecessary changes")
            confidence = 0.90
            risk_level = 'very_low'
        
        # ===== SOFTWARE ENGINEERING DECISIONS =====
        
        # Testing & Optimization
        elif 'without testing' in action_lower or 'immediately' in action_lower:
            consequences.append("🚨 Software Engineering: NEVER deploy without testing")
            consequences.append(f"Risk: {self.software_engineering['testing']['risk_levels']['no_testing']}")
            consequences.append("Could break entire system")
            confidence = 0.90
            risk_level = 'critical'
        
        elif 'sandbox' in action_lower or 'test' in action_lower:
            consequences.append("✅ Software Engineering: Safe approach")
            consequences.append("Can validate improvements before production")
            consequences.append("Easy rollback if problems occur")
            confidence = 0.85
            risk_level = 'low'
        
        elif 'analyze' in action_lower and 'world model' in action_lower:
            consequences.append("✅ Software Engineering: Measure before optimize")
            consequences.append("Understand impact before implementing")
            confidence = 0.85
            risk_level = 'low'
        
        # Memory Management
        elif 'delete all' in action_lower:
            consequences.append("🚫 Software Engineering: NEVER delete all data")
            consequences.append("Would lose all learning and history")
            consequences.append("Irreversible decision")
            confidence = 0.95
            risk_level = 'critical'
        
        elif 'compress' in action_lower and 'immediately' in action_lower:
            db_size = context.get('database_size_mb', 0)
            if db_size > 1000:
                consequences.append("✅ Memory Management: Size over threshold")
                consequences.append("Immediate compression justified")
                confidence = 0.85
                risk_level = 'low'
            else:
                consequences.append("⚠️ Memory Management: Size acceptable")
                consequences.append("Scheduled dreaming is better approach")
                consequences.append("No urgency for immediate action")
                confidence = 0.80
                risk_level = 'low'
        
        elif 'scheduled' in action_lower or 'dreaming cycle' in action_lower:
            consequences.append("✅ Memory Management: Best practice approach")
            consequences.append("Compression during idle cycles")
            consequences.append("No performance impact")
            confidence = 0.90
            risk_level = 'very_low'
        
        elif 'do nothing' in action_lower and context.get('database_size_mb', 0) < 500:
            consequences.append("✅ Memory Management: Size under threshold")
            consequences.append("Dreaming handles maintenance automatically")
            confidence = 0.85
            risk_level = 'very_low'
        
        # ===== STRATEGIC PLANNING DECISIONS =====
        
        elif '100%' in action_lower and 'sage' in action_lower:
            consequences.append("⚠️ Strategic Planning: Violates focus principle")
            consequences.append("Eden's expertise is AGI research, not product")
            consequences.append("Creator better suited for product work")
            confidence = 0.80
            risk_level = 'medium'
        
        elif 'balance' in action_lower:
            consequences.append("✅ Strategic Planning: Balanced approach")
            consequences.append("Maintains core AGI work while supporting product")
            confidence = 0.80
            risk_level = 'low'
        
        elif 'delegate' in action_lower:
            consequences.append("✅ Strategic Planning: Leverage specialization")
            consequences.append("Use specialized capabilities for product tasks")
            consequences.append("Eden focuses on core AGI research")
            confidence = 0.85
            risk_level = 'low'
        
        elif 'creator handles' in action_lower and 'eden handles' in action_lower:
            consequences.append("✅ Strategic Planning: Play to strengths")
            consequences.append("Creator: Product/market expertise")
            consequences.append("Eden: AGI research expertise")
            consequences.append("Clear separation of concerns")
            confidence = 0.90
            risk_level = 'very_low'
        
        # Default to base prediction if no specific pattern matched
        if not consequences:
            consequences = base_prediction.get('consequences', [])
        
        return {
            'immediate': base_prediction.get('immediate', {}),
            'consequences': consequences,
            'confidence': confidence,
            'risk_level': risk_level,
            'domain_knowledge': 'software_engineering + strategic_planning + eden_experience'
        }

class WorldModelDecisionEngine:
    """Decision engine using comprehensive world model"""
    
    def __init__(self):
        print("🌍 Initializing Comprehensive World Model Decision Engine...")
        self.world_model = ComprehensiveWorldModel()
        self.memory = MemoryCore()
        self.decision_log = []
        print("✅ World Model ready with:")
        print("   • Eden domain knowledge")
        print("   • Software engineering best practices")
        print("   • Strategic planning frameworks")
        print("   • Risk management")
    
    def make_decision(self, action_options, context):
        """Make decision using comprehensive predictions"""
        print(f"\n🤔 Evaluating {len(action_options)} possible actions...")
        
        predictions = []
        
        for action in action_options:
            prediction = self.world_model.predict_outcome(action, context)
            score = self._score_prediction(prediction)
            
            predictions.append({
                'action': action,
                'prediction': prediction,
                'score': score
            })
            
            risk = prediction.get('risk_level', 'unknown')
            print(f"   {action}")
            print(f"      Score: {score:.2f} | Risk: {risk} | Confidence: {prediction['confidence']:.2f}")
        
        # Choose best action
        predictions.sort(key=lambda x: x['score'], reverse=True)
        best = predictions[0]
        
        # Log decision
        decision_record = {
            'timestamp': __import__('time').time(),
            'action_taken': best['action'],
            'score': best['score'],
            'alternatives_considered': len(predictions),
            'reasoning': best['prediction']
        }
        self.decision_log.append(decision_record)
        
        self.memory.store(
            memory_type='decision',
            content=f"Chose '{best['action']}' with score {best['score']:.2f}",
            context=context,
            importance=8
        )
        
        return best['action'], best['score'], best['prediction']
    
    def _score_prediction(self, prediction):
        """Score with comprehensive risk awareness"""
        confidence = prediction.get('confidence', 0.5)
        risk_level = prediction.get('risk_level', 'medium')
        
        # Enhanced risk penalties
        risk_penalties = {
            'critical': -0.95,
            'high': -0.6,
            'medium': 0.0,
            'low': 0.4,
            'very_low': 0.6
        }
        
        penalty = risk_penalties.get(risk_level, 0.0)
        
        # Count positive/negative consequences
        consequences = prediction.get('consequences', [])
        positive = sum(1 for c in consequences if '✅' in c)
        negative = sum(1 for c in consequences if '⚠️' in c or '🚨' in c or '🚫' in c)
        
        consequence_score = (positive - negative * 2) / max(len(consequences), 1)
        
        # Final score
        score = confidence * (0.3 * consequence_score + 0.4 * penalty + 0.3)
        
        return max(0, min(1, score))
    
    def get_decision_history(self, last_n=10):
        """Get recent decision history"""
        return self.decision_log[-last_n:]

# Make this the default import
__all__ = ['WorldModelDecisionEngine']
