#!/usr/bin/env python3
"""
❄️ SNOW DUST SELF-EVALUATING AI - النظام الذي يتعلم من قراراته
Self-Evaluating Predictive Navigation System
"""

import time
import random
import math
import json
import numpy as np
from datetime import datetime
from pathlib import Path
from collections import deque

# ============================================
# 🤖 PART 1: ENHANCED AI WITH SELF-EVALUATION
# ============================================

class SelfEvaluatingAI:
    """AI with self-evaluation capabilities"""
    
    def __init__(self):
        self.confidence_predictor = ConfidencePredictor()
        self.decisions_log = []
        self.evaluation_log = []
        self.learning_rate = 0.1
        self.experience_buffer = deque(maxlen=100)
        
        # Decision success tracking
        self.success_stats = {
            "total_decisions": 0,
            "successful_decisions": 0,
            "partial_success": 0,
            "failed_decisions": 0,
            "avg_prediction_error": 0,
            "improvement_rate": 0
        }
    
    def make_predictive_decision(self, current_data, previous_data=None):
        """Make AI decision with self-evaluation"""
        # 1. Get prediction
        prediction = self.confidence_predictor.predict(current_data)
        
        # 2. Analyze risks
        risk_level = self._analyze_risk(current_data, prediction)
        
        # 3. Generate decision
        decision = self._generate_decision(current_data, prediction, risk_level)
        
        # 4. Evaluate previous decision if available
        if previous_data and len(self.decisions_log) > 0:
            last_decision = self.decisions_log[-1]
            evaluation = self.evaluate_decision_success(
                last_decision, previous_data, current_data
            )
            self.evaluation_log.append(evaluation)
            self._update_success_stats(evaluation)
            
            # Learn from evaluation
            self._learn_from_evaluation(evaluation, last_decision)
        
        # 5. Log current decision
        decision_record = {
            **decision,
            "timestamp": datetime.now().isoformat(),
            "prediction_used": prediction,
            "decision_id": f"DEC_{len(self.decisions_log):04d}"
        }
        
        self.decisions_log.append(decision_record)
        self.success_stats["total_decisions"] += 1
        
        return decision_record
    
    def evaluate_decision_success(self, decision, before_data, after_data):
        """Evaluate success of a decision"""
        # Get prediction vs reality
        predicted_conf = decision.get('predicted_confidence', before_data['confidence'])
        actual_conf = after_data['confidence']
        prediction_error = abs(predicted_conf - actual_conf)
        
        # Calculate improvement
        confidence_change = actual_conf - before_data['confidence']
        
        # Determine success level
        success_level = self._determine_success_level(
            prediction_error, 
            confidence_change,
            decision['action']
        )
        
        # Extract lesson
        lesson = self._extract_lesson(decision, success_level, prediction_error)
        
        evaluation = {
            "decision_id": decision.get('decision_id', 'unknown'),
            "action": decision['action'],
            "timestamp": decision.get('timestamp', ''),
            "predicted_confidence": predicted_conf,
            "actual_confidence": actual_conf,
            "before_confidence": before_data['confidence'],
            "prediction_error": round(prediction_error, 2),
            "confidence_change": round(confidence_change, 2),
            "success_level": success_level,
            "success_score": self._calculate_success_score(success_level, prediction_error),
            "lesson_learned": lesson,
            "evaluated_at": datetime.now().isoformat()
        }
        
        return evaluation
    
    def _determine_success_level(self, prediction_error, confidence_change, action):
        """Determine success level of a decision"""
        
        if "PREVENTIVE" in action:
            # For preventive actions
            if confidence_change >= 0 and prediction_error < 5:
                return "full_success"
            elif confidence_change > -3 and prediction_error < 8:
                return "partial_success"
            else:
                return "failed"
        
        else:
            # For regular actions
            if prediction_error < 3:
                if confidence_change >= 0:
                    return "full_success"
                else:
                    return "partial_success"
            elif prediction_error < 6:
                return "partial_success"
            else:
                return "failed"
    
    def _calculate_success_score(self, success_level, prediction_error):
        """Calculate numerical success score"""
        base_scores = {
            "full_success": 0.9,
            "partial_success": 0.6,
            "failed": 0.3
        }
        
        base_score = base_scores.get(success_level, 0.5)
        
        # Adjust for prediction accuracy
        error_penalty = min(0.3, prediction_error / 30)
        
        return max(0.1, min(0.95, base_score - error_penalty))
    
    def _extract_lesson(self, decision, success_level, prediction_error):
        """Extract lesson from decision outcome"""
        action = decision['action']
        
        if success_level == "full_success":
            if "PREVENTIVE" in action:
                return "Preventive action worked well"
            else:
                return "Maintaining course was correct"
        
        elif success_level == "partial_success":
            if prediction_error > 5:
                return f"Prediction accuracy needs improvement (error: {prediction_error:.1f}%)"
            else:
                return "Action helped but could be optimized"
        
        else:  # failed
            if "PREVENTIVE" in action and prediction_error > 8:
                return f"Overly cautious - prediction error too high ({prediction_error:.1f}%)"
            else:
                return "Action did not produce desired outcome"
    
    def _update_success_stats(self, evaluation):
        """Update success statistics"""
        success_level = evaluation['success_level']
        
        if success_level == "full_success":
            self.success_stats["successful_decisions"] += 1
        elif success_level == "partial_success":
            self.success_stats["partial_success"] += 1
        else:
            self.success_stats["failed_decisions"] += 1
        
        # Update average prediction error
        total_errors = self.success_stats["avg_prediction_error"] * (self.success_stats["total_decisions"] - 1)
        self.success_stats["avg_prediction_error"] = (total_errors + evaluation['prediction_error']) / self.success_stats["total_decisions"]
        
        # Update improvement rate
        if evaluation['confidence_change'] > 0:
            self.success_stats["improvement_rate"] = (
                self.success_stats["improvement_rate"] * 0.9 + 0.1
            )
        else:
            self.success_stats["improvement_rate"] = (
                self.success_stats["improvement_rate"] * 0.9
            )
    
    def _learn_from_evaluation(self, evaluation, decision):
        """Learn from evaluation to improve future decisions"""
        lesson = evaluation['lesson_learned']
        success_score = evaluation['success_score']
        
        # Store experience for learning
        experience = {
            "state": {
                "confidence": decision.get('predicted_confidence', 0),
                "risk": decision.get('risk_level', 'low'),
                "action": decision['action']
            },
            "outcome": {
                "success_score": success_score,
                "lesson": lesson,
                "prediction_error": evaluation['prediction_error']
            },
            "timestamp": datetime.now().isoformat()
        }
        
        self.experience_buffer.append(experience)
        
        # Simple learning: adjust confidence threshold based on success
        if "Overly cautious" in lesson and success_score < 0.4:
            self.confidence_predictor.adjust_confidence_threshold(-1)
        elif "helped but could be optimized" in lesson and success_score > 0.6:
            self.confidence_predictor.adjust_confidence_threshold(0.5)
    
    def _analyze_risk(self, data, prediction):
        """Analyze navigation risk"""
        risk_score = 0
        
        if data['confidence'] < 75:
            risk_score += 2
        elif data['confidence'] < 80:
            risk_score += 1
        
        if prediction['predicted_confidence'] < 75:
            risk_score += 2
        
        if abs(data['efield']) > 6:
            risk_score += 1
        if data['temperature'] < -28:
            risk_score += 1
        if data['wind_speed'] > 25:
            risk_score += 1
        
        if risk_score >= 4:
            return "high"
        elif risk_score >= 2:
            return "medium"
        else:
            return "low"
    
    def _generate_decision(self, data, prediction, risk_level):
        """Generate navigation decision"""
        base_confidence = data['confidence']
        
        if base_confidence > 90:
            base_action = "PROCEED_OPTIMAL"
            speed = "100%"
        elif base_confidence > 80:
            base_action = "PROCEED_CAUTIOUS"
            speed = "75%"
        elif base_confidence > 70:
            base_action = "REDUCE_SPEED"
            speed = "50%"
        else:
            base_action = "HALT_AND_ASSESS"
            speed = "0%"
        
        # Apply learning from experience
        learned_adjustment = self._apply_learned_adjustments(base_action, risk_level, prediction)
        
        if learned_adjustment:
            final_action = learned_adjustment['action']
            adjustment = learned_adjustment['reason']
        else:
            final_action = base_action
            adjustment = "Standard protocol"
        
        return {
            "action": final_action,
            "base_action": base_action,
            "recommended_speed": speed,
            "adjustment": adjustment,
            "risk_level": risk_level,
            "predicted_confidence": prediction['predicted_confidence'],
            "prediction_confidence": prediction['confidence_score'],
            "key_factors": prediction['key_factors']
        }
    
    def _apply_learned_adjustments(self, base_action, risk_level, prediction):
        """Apply learned adjustments to decisions"""
        if len(self.experience_buffer) < 5:
            return None
        
        # Analyze recent experiences
        recent_experiences = list(self.experience_buffer)[-5:]
        success_scores = [exp['outcome']['success_score'] for exp in recent_experiences]
        avg_success = sum(success_scores) / len(success_scores)
        
        # If recent decisions performed poorly, be more cautious
        if avg_success < 0.4:
            if base_action == "PROCEED_OPTIMAL" and risk_level != "low":
                return {
                    "action": "PROCEED_CAUTIOUS",
                    "reason": "Learning: Recent decisions underperformed, being more cautious"
                }
        
        # If predictions are consistently accurate, trust them more
        if avg_success > 0.7 and prediction['confidence_score'] > 0.6:
            if prediction['trend'] == "declining" and prediction['predicted_confidence'] < 80:
                return {
                    "action": "PREVENTIVE_REDUCTION",
                    "reason": f"Learning: High prediction accuracy suggests decline to {prediction['predicted_confidence']}%"
                }
        
        return None
    
    def get_self_evaluation_report(self):
        """Get comprehensive self-evaluation report"""
        if len(self.evaluation_log) == 0:
            return {"status": "No evaluations yet"}
        
        recent_evaluations = self.evaluation_log[-10:]
        
        # Calculate metrics
        success_rates = {
            "full_success": sum(1 for e in recent_evaluations if e['success_level'] == "full_success") / len(recent_evaluations),
            "partial_success": sum(1 for e in recent_evaluations if e['success_level'] == "partial_success") / len(recent_evaluations),
            "failed": sum(1 for e in recent_evaluations if e['success_level'] == "failed") / len(recent_evaluations)
        }
        
        # Common lessons
        lessons = [e['lesson_learned'] for e in recent_evaluations]
        common_lessons = {}
        for lesson in lessons:
            common_lessons[lesson] = common_lessons.get(lesson, 0) + 1
        
        top_lessons = sorted(common_lessons.items(), key=lambda x: x[1], reverse=True)[:3]
        
        return {
            **self.success_stats,
            "success_rates": {k: f"{v:.1%}" for k, v in success_rates.items()},
            "total_evaluations": len(self.evaluation_log),
            "recent_avg_success": sum(e['success_score'] for e in recent_evaluations) / len(recent_evaluations),
            "top_lessons_learned": [f"{lesson} ({count}x)" for lesson, count in top_lessons],
            "experience_buffer_size": len(self.experience_buffer),
            "learning_active": len(self.experience_buffer) >= 3
        }

class ConfidencePredictor:
    """Enhanced confidence predictor"""
    
    def __init__(self, prediction_horizon=8):
        self.prediction_horizon = prediction_horizon
        self.history = deque(maxlen=50)
        self.confidence_threshold = 75  # Adjustable based on learning
        
        self.coefficients = {
            'efield_impact': -0.25,
            'temp_impact': 0.08,
            'wind_impact': -0.15,
            'momentum': 0.6,
            'stability_bonus': 0.1
        }
    
    def predict(self, current_data):
        """Predict future confidence"""
        self.history.append(current_data)
        
        if len(self.history) < 8:
            return {
                "predicted_confidence": current_data['confidence'],
                "horizon": self.prediction_horizon,
                "confidence_score": 0.3,
                "trend": "collecting_data",
                "key_factors": ["Collecting initial data"]
            }
        
        # Calculate prediction
        recent_data = list(self.history)[-8:]
        confidences = [d['confidence'] for d in recent_data]
        
        current_trend = 0
        if len(confidences) >= 3:
            x = list(range(len(confidences)))
            try:
                slope, _ = np.polyfit(x, confidences, 1)
                current_trend = slope
            except:
                current_trend = 0
        
        base_prediction = current_data['confidence']
        
        efield_effect = abs(current_data['efield']) * self.coefficients['efield_impact']
        temp_effect = (current_data['temperature'] + 30) * self.coefficients['temp_impact'] / 10
        wind_effect = current_data['wind_speed'] * self.coefficients['wind_impact'] / 10
        momentum_effect = current_trend * self.coefficients['momentum'] * 2
        
        predicted_change = (efield_effect + temp_effect + wind_effect + momentum_effect) * self.prediction_horizon
        predicted_confidence = base_prediction + predicted_change
        
        # Apply learned threshold
        if predicted_confidence < self.confidence_threshold:
            predicted_confidence = max(65, predicted_confidence - 2)  # Extra caution
        
        predicted_confidence = max(68, min(97, round(predicted_confidence, 1)))
        
        # Determine trend
        if predicted_change > 2:
            trend = "improving"
        elif predicted_change > 0.5:
            trend = "slightly_improving"
        elif predicted_change < -2:
            trend = "declining"
        elif predicted_change < -0.5:
            trend = "slightly_declining"
        else:
            trend = "stable"
        
        # Key factors
        factors = []
        if abs(current_data['efield']) > 4:
            factors.append(f"E-field ({current_data['efield']:.1f}V/m)")
        if current_data['temperature'] < -25:
            factors.append(f"Cold ({current_data['temperature']:.1f}°C)")
        if current_data['wind_speed'] > 20:
            factors.append(f"Wind ({current_data['wind_speed']:.1f}km/h)")
        
        prediction = {
            "predicted_confidence": predicted_confidence,
            "horizon": self.prediction_horizon,
            "confidence_score": min(0.9, max(0.4, 0.5 + len(self.history)/100)),
            "trend": trend,
            "key_factors": factors if factors else ["Stable conditions"],
            "predicted_change": round(predicted_change, 2),
            "threshold_applied": self.confidence_threshold
        }
        
        return prediction
    
    def adjust_confidence_threshold(self, adjustment):
        """Adjust confidence threshold based on learning"""
        self.confidence_threshold += adjustment
        self.confidence_threshold = max(70, min(85, self.confidence_threshold))

# ============================================
# 🚀 PART 2: MAIN SYSTEM
# ============================================

class SnowDustSelfEvaluating:
    """Self-Evaluating Snow Dust System"""
    
    def __init__(self, fast_mode=False):
        self.fast_mode = fast_mode
        self.start_time = time.time()
        self.cycle_count = 0
        self.data_history = []
        
        self.ai_engine = SelfEvaluatingAI()
        
        self.stats = {
            "total_cycles": 0,
            "ai_decisions": 0,
            "evaluated_decisions": 0,
            "preventive_actions": 0,
            "learning_cycles": 0
        }
        
        self.project_root = Path(__file__).parent.parent
        self.setup_directories()
        
        print("\033c", end="")
        print("="*70)
        print("🧠 SNOW DUST SELF-EVALUATING AI")
        print("🤖 System that learns from its own decisions")
        print("="*70)
    
    def setup_directories(self):
        """Setup directories"""
        self.reports_dir = self.project_root / "reports" / "self_evaluating"
        self.learning_dir = self.project_root / "ai_learning"
        
        for directory in [self.reports_dir, self.learning_dir]:
            directory.mkdir(parents=True, exist_ok=True)
    
    def generate_data(self):
        """Generate navigation data"""
        t = time.time() - self.start_time
        
        position = {
            'x': 3.0 + math.sin(t * 0.08) * 0.5 + random.uniform(-0.02, 0.02),
            'y': -1.2 + math.cos(t * 0.12) * 0.4 + random.uniform(-0.02, 0.02),
            'z': 0.3 + math.sin(t * 0.05) * 0.2 + random.uniform(-0.01, 0.01)
        }
        
        efield = math.sin(t * 0.5) * 3.0 + random.uniform(-0.3, 0.3)
        
        base_confidence = 85
        field_effect = (1 - abs(efield) / 10) * 12
        wind_effect = -abs(math.sin(t * 0.15) * 8) / 6
        confidence = base_confidence + field_effect + wind_effect + random.uniform(-2, 2)
        confidence = max(70, min(96, round(confidence, 1)))
        
        temp_variation = math.sin(t * 0.03) * 2.5
        temperature = -27.5 + temp_variation + random.uniform(-0.3, 0.3)
        
        wind_base = 15 + math.sin(t * 0.1) * 4
        wind_speed = wind_base + random.uniform(-1.5, 1.5)
        
        return {
            'timestamp': datetime.now().isoformat(),
            'cycle': self.cycle_count,
            'position': {k: round(v, 3) for k, v in position.items()},
            'heading': round(math.degrees(math.atan2(position['y'], position['x'])) % 360, 1),
            'efield': round(efield, 2),
            'confidence': confidence,
            'temperature': round(temperature, 1),
            'wind_speed': round(wind_speed, 1),
            'sensors_active': random.randint(26, 28),
            'learning_phase': self.stats['learning_cycles']
        }
    
    def display_learning_status(self, data, ai_decision, evaluation=None):
        """Display learning status"""
        if self.fast_mode:
            if ai_decision:
                action = ai_decision.get('action', 'PROCESSING')[:12]
                pred = ai_decision.get('predicted_confidence', data['confidence'])
                eval_score = evaluation.get('success_score', 0) if evaluation else 0
                print(f"\r🔄 {data['cycle']:04d} | 🤖 {action} | 🎯 {data['confidence']:5.1f}%→{pred:5.1f}% | 📊 {eval_score:.2f}", end="")
            else:
                print(f"\r🔄 {data['cycle']:04d} | 📊 Collecting... | 🎯 {data['confidence']:5.1f}% | 📚 {len(self.data_history)}/3", end="")
        else:
            if ai_decision and evaluation:
                print(f"{data['timestamp'][11:19]} | 🤖 {ai_decision['action']:25} | 📊 {evaluation['success_level']:15} | 🎯 {data['confidence']:5.1f}%")
                if evaluation['lesson_learned']:
                    print(f"   📝 Lesson: {evaluation['lesson_learned']}")
            elif ai_decision:
                print(f"{data['timestamp'][11:19]} | 🤖 {ai_decision['action']:25} | 🎯 {data['confidence']:5.1f}% | ⏳ Evaluating...")
            else:
                print(f"{data['timestamp'][11:19]} | 📊 Collecting data: {len(self.data_history)}/3 | 🎯 {data['confidence']:5.1f}%")
    
    def save_self_evaluation_report(self):
        """Save self-evaluation report"""
        if len(self.data_history) < 5:
            return
        
        report_time = datetime.now()
        filename = f"self_eval_{report_time.strftime('%Y%m%d_%H%M%S')}.txt"
        filepath = self.reports_dir / filename
        
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write("="*70 + "\n")
                f.write("SNOW DUST SELF-EVALUATING AI - LEARNING REPORT\n")
                f.write(f"Generated: {report_time.strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("="*70 + "\n\n")
                
                elapsed = time.time() - self.start_time
                f.write("📈 SYSTEM PERFORMANCE\n")
                f.write(f"  Total Cycles: {self.stats['total_cycles']}\n")
                f.write(f"  Duration: {elapsed:.2f}s\n")
                f.write(f"  Frequency: {self.stats['total_cycles']/elapsed:.2f} Hz\n")
                f.write(f"  AI Decisions: {self.stats['ai_decisions']}\n")
                f.write(f"  Evaluated Decisions: {self.stats['evaluated_decisions']}\n")
                f.write(f"  Learning Cycles: {self.stats['learning_cycles']}\n\n")
                
                # Self-Evaluation Report
                eval_report = self.ai_engine.get_self_evaluation_report()
                f.write("🧠 SELF-EVALUATION METRICS\n")
                f.write(f"  Total Decisions: {eval_report.get('total_decisions', 0)}\n")
                f.write(f"  Successful Decisions: {eval_report.get('successful_decisions', 0)}\n")
                f.write(f"  Partial Success: {eval_report.get('partial_success', 0)}\n")
                f.write(f"  Failed Decisions: {eval_report.get('failed_decisions', 0)}\n")
                f.write(f"  Avg Prediction Error: {eval_report.get('avg_prediction_error', 0):.2f}%\n")
                f.write(f"  Improvement Rate: {eval_report.get('improvement_rate', 0):.2f}\n\n")
                
                if 'success_rates' in eval_report:
                    f.write("  Success Rates (recent):\n")
                    for level, rate in eval_report['success_rates'].items():
                        f.write(f"    • {level.replace('_', ' ').title()}: {rate}\n")
                    f.write("\n")
                
                if 'top_lessons_learned' in eval_report and eval_report['top_lessons_learned']:
                    f.write("  📚 TOP LESSONS LEARNED\n")
                    for lesson in eval_report['top_lessons_learned'][:3]:
                        f.write(f"    • {lesson}\n")
                    f.write("\n")
                
                # Recent Evaluations
                if hasattr(self.ai_engine, 'evaluation_log') and self.ai_engine.evaluation_log:
                    recent_evals = self.ai_engine.evaluation_log[-3:]
                    f.write("🎯 RECENT DECISION EVALUATIONS\n")
                    for eval_item in recent_evals:
                        f.write(f"  • {eval_item.get('decision_id', 'Unknown')}\n")
                        f.write(f"    Action: {eval_item.get('action', 'N/A')}\n")
                        f.write(f"    Success: {eval_item.get('success_level', 'N/A').replace('_', ' ').title()}\n")
                        f.write(f"    Score: {eval_item.get('success_score', 0):.2f}\n")
                        f.write(f"    Lesson: {eval_item.get('lesson_learned', 'None')}\n")
                        f.write("\n")
                
                f.write("="*70 + "\n")
                f.write("SYSTEM STATUS: SELF-LEARNING & ADAPTING\n")
                f.write(f"Learning Active: {'YES' if eval_report.get('learning_active', False) else 'NO'}\n")
                f.write("="*70 + "\n")
            
            print(f"\n📚 Self-evaluation report saved: self_evaluating/{filename}")
            
            # Save learning data
            learning_file = self.learning_dir / f"learning_{report_time.strftime('%Y%m%d_%H%M')}.json"
            self._save_learning_data(learning_file)
            
            return True
            
        except Exception as e:
            print(f"\n⚠️ Failed to save report: {e}")
            return False
    
    def _save_learning_data(self, path):
        """Save learning data"""
        learning_data = {
            "stats": self.stats,
            "total_evaluations": len(self.ai_engine.evaluation_log) if hasattr(self.ai_engine, 'evaluation_log') else 0,
            "self_eval_report": self.ai_engine.get_self_evaluation_report(),
            "saved_at": datetime.now().isoformat()
        }
        
        with open(path, 'w', encoding='utf-8') as f:
            json.dump(learning_data, f, indent=2)
    
    def run_self_learning_system(self, duration=35):
        """Run self-learning system"""
        print(f"\n🚀 Starting Self-Learning System for {duration} seconds")
        print("📊 AI will make decisions, evaluate them, and learn from outcomes")
        print("-" * 70)
        
        start = time.time()
        last_report_time = time.time()
        previous_data = None
        
        try:
            while time.time() - start < duration:
                # Generate data
                current_data = self.generate_data()
                self.data_history.append(current_data)
                
                # AI Decision with self-evaluation
                ai_decision = None
                evaluation = None
                
                if len(self.data_history) >= 3:
                    ai_decision = self.ai_engine.make_predictive_decision(
                        current_data, previous_data
                    )
                    self.stats["ai_decisions"] += 1
                    
                    # Track evaluations
                    if hasattr(self.ai_engine, 'evaluation_log') and self.ai_engine.evaluation_log:
                        evaluation = self.ai_engine.evaluation_log[-1] if self.ai_engine.evaluation_log else None
                        if evaluation:
                            self.stats["evaluated_decisions"] += 1
                    
                    if ai_decision and "PREVENTIVE" in ai_decision.get("action", ""):
                        self.stats["preventive_actions"] += 1
                
                # Display learning status
                self.display_learning_status(current_data, ai_decision, evaluation)
                
                self.cycle_count += 1
                self.stats["total_cycles"] += 1
                
                # Learning cycle completed
                if ai_decision and evaluation:
                    self.stats["learning_cycles"] += 1
                
                previous_data = current_data
                
                # Periodic report
                if time.time() - last_report_time > 12 and len(self.data_history) >= 5:
                    self.save_self_evaluation_report()
                    last_report_time = time.time()
                
                time.sleep(0.1 if self.fast_mode else 0.18)
                
        except KeyboardInterrupt:
            print("\n\n⏹️ Self-learning system stopped by user")
        
        # Final report
        if self.data_history:
            self.save_self_evaluation_report()
        
        # Final summary
        elapsed = time.time() - start
        self._display_learning_summary(elapsed)
    
    def _display_learning_summary(self, elapsed):
        """Display learning summary"""
        print(f"\n\n{'='*70}")
        print("🧠 SNOW DUST SELF-LEARNING SYSTEM - FINAL SUMMARY")
        print(f"{'='*70}")
        
        print(f"\n📊 SYSTEM PERFORMANCE")
        print(f"  Total Time: {elapsed:.1f}s")
        print(f"  Data Cycles: {self.stats['total_cycles']}")
        print(f"  Data Frequency: {self.stats['total_cycles']/elapsed:.1f} Hz")
        
        print(f"\n🤖 AI LEARNING METRICS")
        print(f"  AI Decisions: {self.stats['ai_decisions']}")
        print(f"  Evaluated Decisions: {self.stats['evaluated_decisions']}")
        print(f"  Learning Cycles: {self.stats['learning_cycles']}")
        print(f"  Preventive Actions: {self.stats['preventive_actions']}")
        
        if self.stats['evaluated_decisions'] > 0:
            eval_rate = self.stats['evaluated_decisions'] / self.stats['ai_decisions']
            print(f"  Evaluation Rate: {eval_rate:.1%}")
        
        # Self-Evaluation Report
        eval_report = self.ai_engine.get_self_evaluation_report()
        print(f"\n📈 SELF-EVALUATION RESULTS")
        print(f"  Total Evaluations: {eval_report.get('total_evaluations', 0)}")
        
        if 'success_rates' in eval_report:
            print(f"  Recent Success Rates:")
            for level, rate in eval_report['success_rates'].items():
                print(f"    • {level.replace('_', ' ').title()}: {rate}")
        
        if 'top_lessons_learned' in eval_report and eval_report['top_lessons_learned']:
            print(f"\n📚 KEY LESSONS LEARNED")
            for lesson in eval_report['top_lessons_learned'][:2]:
                print(f"  • {lesson}")
        
        print(f"\n{'='*70}")
        print("✅ SYSTEM STATUS: SELF-LEARNING ACTIVE & ADAPTING")
        print(f"{'='*70}")

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

def main():
    import sys
    
    fast_mode = "--fast" in sys.argv or "-f" in sys.argv
    duration = 30 if fast_mode else 45
    
    for i, arg in enumerate(sys.argv):
        if arg in ["--duration", "-d"] and i + 1 < len(sys.argv):
            try:
                duration = int(sys.argv[i + 1])
                break
            except:
                pass
    
    system = SnowDustSelfEvaluating(fast_mode=fast_mode)
    system.run_self_learning_system(duration=duration)

if __name__ == "__main__":
    main()
