"""
Eden Core - Integrated Robustness Framework
Integrates: Error handling, validation, security, state management
"""

import sys
import time
from typing import Any, Callable, Dict, Optional
from datetime import datetime

# Import all robustness modules
from eden_robust_error_handler import (
    RobustErrorHandler, ErrorSeverity, RecoveryStrategy
)
from eden_validation_monitoring import (
    RobustSystemManager as ValidationManager,
    HealthMetrics
)
from eden_security_safety import (
    RobustSecuritySystem, PermissionLevel
)
from eden_state_management import (
    RobustStateSystem
)


class EdenRobustCore:
    """
    Integrated robustness framework for Eden Core
    
    Provides comprehensive protection through:
    - Error handling & recovery
    - Input validation & output verification
    - Security & safety constraints
    - State management & crash recovery
    - System monitoring & health checks
    """
    
    def __init__(self, config: Optional[Dict] = None):
        self.config = config or {}
        
        # Initialize all robustness systems
        print("🔧 Initializing Eden Robust Core...")
        
        self.error_handler = RobustErrorHandler()
        self.validator = ValidationManager()
        self.security = RobustSecuritySystem()
        self.state_system = RobustStateSystem()
        
        # Setup crash recovery
        self.state_system.crash_recovery.register_shutdown_hook(
            self._graceful_shutdown_hook
        )
        
        # Configuration
        self.debug_mode = self.config.get('debug', False)
        self.auto_checkpoint = self.config.get('auto_checkpoint', True)
        self.checkpoint_interval = self.config.get('checkpoint_interval', 100)
        self.operation_count = 0
        
        print("✅ Eden Robust Core initialized successfully")
    
    def execute_robust_operation(self, 
                                operation: Callable,
                                operation_name: str,
                                input_data: Any,
                                input_type: str = "generic",
                                output_type: str = "generic",
                                permission_level: PermissionLevel = PermissionLevel.LIMITED_WRITE,
                                create_checkpoint: bool = False) -> Dict[str, Any]:
        """
        Execute an operation with full robustness protection
        
        This is the main entry point for executing operations with:
        - Input validation
        - Security authorization
        - Error handling with recovery
        - Output verification
        - State management
        - Performance monitoring
        
        Args:
            operation: Function to execute
            operation_name: Name of the operation
            input_data: Input data for the operation
            input_type: Type of input for validation
            output_type: Expected output type for verification
            permission_level: Required permission level
            create_checkpoint: Whether to create state checkpoint
        
        Returns:
            Dict with keys: success, result, metadata (validation, security, performance)
        """
        start_time = time.time()
        self.operation_count += 1
        
        metadata = {
            'operation_name': operation_name,
            'start_time': datetime.now().isoformat(),
            'operation_count': self.operation_count
        }
        
        try:
            # Step 1: Input Validation
            validation_result = self.validator.input_validator.validate(input_type, input_data)
            metadata['validation'] = validation_result
            
            if not validation_result['valid']:
                return self._create_failure_response(
                    "Input validation failed",
                    metadata,
                    start_time
                )
            
            # Step 2: Security Authorization
            action = {
                'type': operation_name,
                'input': str(input_data)[:100],  # Truncate for security log
                'timestamp': datetime.now().isoformat()
            }
            
            auth_result = self.security.authorize_action(action, permission_level)
            metadata['security'] = auth_result
            
            if not auth_result['authorized']:
                return self._create_failure_response(
                    f"Authorization failed: {auth_result['reason']}",
                    metadata,
                    start_time
                )
            
            # Step 3: Create checkpoint if requested
            if create_checkpoint or (self.auto_checkpoint and self.operation_count % self.checkpoint_interval == 0):
                self.state_system.state_manager.create_snapshot(metadata={
                    'operation': operation_name,
                    'operation_count': self.operation_count
                })
                metadata['checkpoint_created'] = True
            
            # Step 4: Execute Operation with Error Handling
            try:
                result = operation(input_data)
                metadata['execution'] = {'status': 'success'}
            except Exception as e:
                # Use error handler for recovery
                error_context = {
                    'operation_name': operation_name,
                    'input_data': str(input_data)[:100]
                }
                
                recovery_result = self.error_handler.handle_error(
                    e,
                    error_context,
                    severity=ErrorSeverity.HIGH,
                    strategy=RecoveryStrategy.RETRY
                )
                
                metadata['error_recovery'] = recovery_result
                
                if not recovery_result['success']:
                    return self._create_failure_response(
                        f"Operation failed: {str(e)}",
                        metadata,
                        start_time,
                        error=e
                    )
                
                result = recovery_result.get('result')
            
            # Step 5: Output Verification
            verification_result = self.validator.output_verifier.verify(output_type, result)
            metadata['verification'] = verification_result
            
            if not verification_result['verified']:
                return self._create_failure_response(
                    "Output verification failed",
                    metadata,
                    start_time
                )
            
            # Step 6: Record metrics
            duration = time.time() - start_time
            self.validator.system_monitor.record_operation(duration, success=True)
            
            metadata['performance'] = {
                'duration_seconds': duration,
                'end_time': datetime.now().isoformat()
            }
            
            return {
                'success': True,
                'result': result,
                'metadata': metadata
            }
            
        except Exception as e:
            # Catch-all for unexpected errors
            duration = time.time() - start_time
            self.validator.system_monitor.record_operation(duration, success=False)
            
            return self._create_failure_response(
                f"Unexpected error: {str(e)}",
                metadata,
                start_time,
                error=e
            )
    
    def _create_failure_response(self, reason: str, metadata: Dict, 
                                start_time: float, error: Optional[Exception] = None) -> Dict[str, Any]:
        """Create a standardized failure response"""
        duration = time.time() - start_time
        self.validator.system_monitor.record_operation(duration, success=False)
        
        metadata['performance'] = {
            'duration_seconds': duration,
            'end_time': datetime.now().isoformat()
        }
        
        response = {
            'success': False,
            'reason': reason,
            'metadata': metadata
        }
        
        if error and self.debug_mode:
            response['error_details'] = str(error)
        
        return response
    
    def get_state(self, key: str, default: Any = None) -> Any:
        """Get state value"""
        return self.state_system.state_manager.get_state(key, default)
    
    def update_state(self, key: str, value: Any, create_snapshot: bool = False):
        """Update state value"""
        self.state_system.state_manager.update_state(key, value, create_snapshot)
    
    def create_checkpoint(self, label: str = "manual") -> str:
        """Create a labeled checkpoint"""
        snapshot = self.state_system.state_manager.create_snapshot(metadata={
            'operation': 'manual_checkpoint',
            'label': label
        })
        return snapshot.snapshot_id
    
    def rollback(self, steps: int = 1) -> bool:
        """Rollback state by number of steps"""
        return self.state_system.state_manager.rollback_steps(steps)
    
    def get_health_status(self) -> Dict[str, Any]:
        """Get current system health status"""
        return self.validator.system_monitor.get_health_status()
    
    def get_comprehensive_report(self) -> str:
        """Generate comprehensive report of all systems"""
        report = f"""
╔══════════════════════════════════════════════════════════════╗
║         EDEN CORE - COMPREHENSIVE ROBUSTNESS REPORT          ║
╚══════════════════════════════════════════════════════════════╝

Generated: {datetime.now().isoformat()}
Total Operations: {self.operation_count}

"""
        
        # Health Status
        health = self.get_health_status()
        report += f"""
┌─────────────────────────────────────┐
│         HEALTH STATUS               │
└─────────────────────────────────────┘
Status: {'🟢 HEALTHY' if health['healthy'] else '🔴 UNHEALTHY'}
CPU Usage: {health['current']['cpu']:.1f}%
Memory Usage: {health['current']['memory']:.1f}%
Error Rate: {health['current']['error_rate']:.2%}
Avg Response Time: {health['current']['response_time']:.3f}s

"""
        
        # Error Statistics
        error_stats = self.error_handler.get_error_statistics()
        report += f"""
┌─────────────────────────────────────┐
│      ERROR HANDLING SUMMARY         │
└─────────────────────────────────────┘
Total Errors: {error_stats.get('total_errors', 0)}
"""
        
        if error_stats.get('by_severity'):
            report += "Errors by Severity:\n"
            for severity, count in error_stats['by_severity'].items():
                report += f"  - {severity}: {count}\n"
        
        # Security Summary
        report += f"""
┌─────────────────────────────────────┐
│       SECURITY SUMMARY              │
└─────────────────────────────────────┘
Total Authorizations: {len(self.security.audit_log)}
Approved: {sum(1 for a in self.security.audit_log if a.approved)}
Denied: {sum(1 for a in self.security.audit_log if not a.approved)}

"""
        
        # State Management
        state_history = self.state_system.state_manager.get_state_history()
        report += f"""
┌─────────────────────────────────────┐
│      STATE MANAGEMENT               │
└─────────────────────────────────────┘
State Keys: {len(self.state_system.state_manager.current_state)}
Snapshots: {len(state_history)}
Latest Snapshot: {state_history[-1]['timestamp'] if state_history else 'N/A'}

"""
        
        # Recommendations
        report += """
┌─────────────────────────────────────┐
│       RECOMMENDATIONS               │
└─────────────────────────────────────┘
"""
        
        if health['current']['cpu'] > 70:
            report += "⚠️  High CPU usage detected - optimize compute operations\n"
        if health['current']['memory'] > 75:
            report += "⚠️  High memory usage - review memory management\n"
        if error_stats.get('total_errors', 0) > 10:
            report += "⚠️  Multiple errors detected - review error logs\n"
        if health['healthy']:
            report += "✅ All systems operating normally\n"
        
        report += "\n" + "="*64 + "\n"
        
        return report
    
    def _graceful_shutdown_hook(self):
        """Hook for graceful shutdown"""
        print("Eden Robust Core: Executing graceful shutdown...")
        # Save any critical state
        self.state_system.state_manager.create_snapshot(metadata={
            'operation': 'shutdown',
            'operations_completed': self.operation_count
        })
    
    def shutdown(self):
        """Gracefully shutdown the system"""
        print("🛑 Initiating graceful shutdown...")
        self.state_system.crash_recovery.graceful_shutdown()
        print("✅ Shutdown complete")


# Example usage and demonstration
if __name__ == "__main__":
    print("="*64)
    print("   EDEN CORE - INTEGRATED ROBUSTNESS FRAMEWORK DEMO")
    print("="*64 + "\n")
    
    # Initialize the robust core
    eden = EdenRobustCore(config={
        'debug': True,
        'auto_checkpoint': True,
        'checkpoint_interval': 5
    })
    
    # Example operations
    def sample_learning_operation(data):
        """Simulate a learning operation"""
        time.sleep(0.1)  # Simulate processing
        return {
            'learned': True,
            'accuracy': 0.95,
            'data_processed': len(str(data))
        }
    
    def sample_reasoning_operation(data):
        """Simulate a reasoning operation"""
        time.sleep(0.05)
        return {
            'conclusion': f"Analyzed: {data}",
            'confidence': 0.88
        }
    
    # Execute robust operations
    print("\n📊 Executing robust operations...\n")
    
    for i in range(3):
        result = eden.execute_robust_operation(
            operation=sample_learning_operation,
            operation_name="meta_learning",
            input_data=f"training_batch_{i}",
            input_type="query",
            output_type="reasoning_result",
            permission_level=PermissionLevel.LIMITED_WRITE,
            create_checkpoint=(i == 2)  # Checkpoint on last operation
        )
        
        print(f"Operation {i+1}: {'✅ SUCCESS' if result['success'] else '❌ FAILED'}")
        if result['success']:
            print(f"  Result: {result['result']}")
            print(f"  Duration: {result['metadata']['performance']['duration_seconds']:.3f}s")
        print()
    
    # Update some state
    print("📝 Updating system state...\n")
    eden.update_state('model_version', 'v3.0')
    eden.update_state('capabilities', ['reasoning', 'learning', 'planning', 'reflection'])
    eden.update_state('training_iterations', 1000)
    
    # Get health status
    print("🏥 System Health Check...\n")
    health = eden.get_health_status()
    print(f"Health Status: {'🟢 HEALTHY' if health['healthy'] else '🔴 UNHEALTHY'}")
    print(f"CPU: {health['current']['cpu']:.1f}% ({health['trends']['cpu_trend']})")
    print(f"Memory: {health['current']['memory']:.1f}% ({health['trends']['memory_trend']})")
    print()
    
    # Generate comprehensive report
    print(eden.get_comprehensive_report())
    
    # Demonstrate rollback
    print("\n⏮️  Demonstrating state rollback...\n")
    print(f"Current model version: {eden.get_state('model_version')}")
    eden.rollback(steps=1)
    print(f"After rollback: {eden.get_state('model_version')}")
    print()
    
    # Graceful shutdown
    eden.shutdown()
    
    print("\n" + "="*64)
    print("   DEMO COMPLETE")
    print("="*64)
