#!/usr/bin/env python3
"""
❄️ SNOW DUST AI COMPLETE - Self-Evaluating Navigation System
With Daily Reports and Learning Capabilities
"""

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

# ============================================
# 📊 REPORT MANAGER
# ============================================

class ReportManager:
    """Manages daily reports and logs"""
    
    def __init__(self, base_dir="../reports"):
        self.base_dir = Path(base_dir)
        self.daily_dir = self.base_dir / "daily"
        self.learning_dir = Path("../ai_learning")
        self.logs_dir = Path("../logs")
        
        # Create directories
        for directory in [self.base_dir, self.daily_dir, self.learning_dir, self.logs_dir]:
            directory.mkdir(parents=True, exist_ok=True)
        
        # Current report
        self.current_date = datetime.now().date()
        self.daily_report = {
            "date": str(self.current_date),
            "start_time": datetime.now().isoformat(),
            "total_cycles": 0,
            "total_decisions": 0,
            "total_evaluations": 0,
            "average_accuracy": 0,
            "prediction_stats": {},
            "decision_stats": {},
            "learning_progress": {},
            "system_performance": [],
            "session_history": []
        }
    
    def update_report(self, stats, cycle_data=None):
        """Update daily report with new stats"""
        # Check if new day
        current_date = datetime.now().date()
        if current_date != self.current_date:
            self.save_daily_report()
            self.current_date = current_date
            self.daily_report = {
                "date": str(self.current_date),
                "start_time": datetime.now().isoformat(),
                "total_cycles": 0,
                "total_decisions": 0,
                "total_evaluations": 0,
                "average_accuracy": 0,
                "prediction_stats": {},
                "decision_stats": {},
                "learning_progress": {},
                "system_performance": [],
                "session_history": []
            }
        
        # Update stats
        self.daily_report["total_cycles"] = stats.get("cycles", 0)
        self.daily_report["total_decisions"] = stats.get("decision", {}).get("total_decisions", 0)
        self.daily_report["total_evaluations"] = stats.get("evaluation", {}).get("total_evaluations", 0)
        self.daily_report["average_accuracy"] = stats.get("evaluation", {}).get("average_accuracy", 0)
        self.daily_report["prediction_stats"] = stats.get("prediction", {})
        self.daily_report["decision_stats"] = stats.get("decision", {})
        self.daily_report["learning_progress"] = stats.get("learning", {})
        
        # Add performance snapshot
        perf_snapshot = {
            "timestamp": datetime.now().isoformat(),
            "cycle": stats.get("cycles", 0),
            "confidence": cycle_data.get("confidence", 0) if cycle_data else 0,
            "evaluations": stats.get("evaluation", {}).get("total_evaluations", 0),
            "avg_accuracy": stats.get("evaluation", {}).get("average_accuracy", 0)
        }
        self.daily_report["system_performance"].append(perf_snapshot)
        
        # Keep only last 100 snapshots
        if len(self.daily_report["system_performance"]) > 100:
            self.daily_report["system_performance"] = self.daily_report["system_performance"][-100:]
    
    def add_session_record(self, session_type, duration, cycles, avg_accuracy):
        """Add session record to history"""
        session_record = {
            "timestamp": datetime.now().isoformat(),
            "session_type": session_type,
            "duration_seconds": duration,
            "total_cycles": cycles,
            "average_accuracy": avg_accuracy
        }
        self.daily_report["session_history"].append(session_record)
    
    def save_daily_report(self):
        """Save daily report to file"""
        if not self.daily_report.get("session_history"):
            return
        
        self.daily_report["end_time"] = datetime.now().isoformat()
        
        # Calculate session totals
        total_sessions = len(self.daily_report["session_history"])
        total_duration = sum(s.get("duration_seconds", 0) for s in self.daily_report["session_history"])
        total_cycles = sum(s.get("total_cycles", 0) for s in self.daily_report["session_history"])
        
        self.daily_report["daily_summary"] = {
            "total_sessions": total_sessions,
            "total_duration_hours": round(total_duration / 3600, 2),
            "total_cycles": total_cycles,
            "avg_accuracy": self.daily_report.get("average_accuracy", 0)
        }
        
        # Save report
        filename = f"daily_report_{self.current_date}.json"
        report_path = self.daily_dir / filename
        
        with open(report_path, 'w', encoding='utf-8') as f:
            json.dump(self.daily_report, f, indent=2, ensure_ascii=False)
        
        print(f"\n📊 Daily report saved: {report_path}")
        return report_path
    
    def save_learning_data(self, ai_system, session_id):
        """Save AI learning data"""
        learning_data = {
            "session_id": session_id,
            "timestamp": datetime.now().isoformat(),
            "total_cycles": ai_system.cycles,
            "evaluation_stats": ai_system.ai.self_evaluator.get_evaluation_stats(),
            "decision_stats": ai_system.ai.get_decision_stats(),
            "learning_progress": ai_system.ai.self_evaluator.get_learning_progress()
        }
        
        filename = f"learning_session_{session_id}.json"
        learning_path = self.learning_dir / filename
        
        with open(learning_path, 'w', encoding='utf-8') as f:
            json.dump(learning_data, f, indent=2, ensure_ascii=False)
        
        return learning_path
    
    def get_todays_report_path(self):
        """Get today's report file path"""
        return self.daily_dir / f"daily_report_{self.current_date}.json"

# ============================================
# 🧠 AI SELF-EVALUATION MODULE
# ============================================

class AISelfEvaluator:
    def __init__(self):
        self.evaluation_log = []
        self.learning_rate = 0.1
        self.adaptation_factors = {
            'efield_sensitivity': 1.0,
            'temp_sensitivity': 1.0,
            'wind_sensitivity': 1.0,
            'trend_weight': 1.0
        }
        
    def evaluate_outcome(self, past_prediction, actual_data):
        """Evaluate prediction outcome"""
        predicted = past_prediction.get("predicted_confidence")
        actual = actual_data.get("confidence")
        
        if predicted is None or actual is None:
            return None
        
        error = round(actual - predicted, 2)
        absolute_error = abs(error)
        accuracy = max(0, 100 - absolute_error * 5)
        
        # Determine success level
        if absolute_error < 3:
            success_level = "EXCELLENT"
            success_score = 0.9
        elif absolute_error < 6:
            success_level = "GOOD"
            success_score = 0.7
        elif absolute_error < 10:
            success_level = "FAIR"
            success_score = 0.5
        else:
            success_level = "POOR"
            success_score = 0.3
        
        evaluation = {
            "timestamp": datetime.now().isoformat(),
            "predicted_confidence": predicted,
            "actual_confidence": actual,
            "error": error,
            "absolute_error": absolute_error,
            "accuracy_score": round(accuracy, 1),
            "success_level": success_level,
            "success_score": success_score,
            "conditions": {
                "efield": actual_data.get('efield', 0),
                "temperature": actual_data.get('temperature', 0),
                "wind_speed": actual_data.get('wind_speed', 0)
            }
        }
        
        self.evaluation_log.append(evaluation)
        self._adapt_learning(evaluation)
        
        return evaluation
    
    def _adapt_learning(self, evaluation):
        """Adapt learning based on evaluation"""
        error = evaluation['absolute_error']
        conditions = evaluation['conditions']
        
        if error > 5:
            # If error is large, adjust sensitivities
            if abs(conditions['efield']) > 4:
                self.adaptation_factors['efield_sensitivity'] *= 1.1
            if abs(conditions['temperature']) > 25:
                self.adaptation_factors['temp_sensitivity'] *= 1.05
            if conditions['wind_speed'] > 20:
                self.adaptation_factors['wind_sensitivity'] *= 1.08
        
        elif error < 2:
            # If prediction is accurate, maintain settings
            pass
    
    def get_evaluation_stats(self):
        """Get evaluation statistics"""
        if not self.evaluation_log:
            return {
                "total_evaluations": 0,
                "average_error": 0,
                "average_accuracy": 0,
                "success_distribution": {}
            }
        
        recent = self.evaluation_log[-10:] if len(self.evaluation_log) > 10 else self.evaluation_log
        
        avg_error = sum(abs(e["error"]) for e in recent) / len(recent)
        avg_accuracy = sum(e["accuracy_score"] for e in recent) / len(recent)
        
        # Success distribution
        success_levels = {}
        for e in recent:
            level = e["success_level"]
            success_levels[level] = success_levels.get(level, 0) + 1
        
        return {
            "total_evaluations": len(self.evaluation_log),
            "recent_evaluations": len(recent),
            "average_error": round(avg_error, 2),
            "average_accuracy": round(avg_accuracy, 1),
            "success_distribution": {k: f"{(v/len(recent))*100:.1f}%" for k, v in success_levels.items()},
            "learning_adaptations": self.adaptation_factors
        }
    
    def get_learning_progress(self):
        """Track learning progress"""
        if len(self.evaluation_log) < 5:
            return {"status": "Collecting data", "confidence": 0.3}
        
        recent = self.evaluation_log[-5:]
        avg_score = sum(e["success_score"] for e in recent) / len(recent)
        
        if avg_score > 0.8:
            status = "Excellent Learning"
            confidence = 0.9
        elif avg_score > 0.6:
            status = "Good Learning"
            confidence = 0.7
        elif avg_score > 0.4:
            status = "Continuous Learning"
            confidence = 0.5
        else:
            status = "Needs Improvement"
            confidence = 0.3
        
        return {
            "status": status,
            "confidence": confidence,
            "avg_success_score": round(avg_score, 2),
            "adaptation_active": any(v != 1.0 for v in self.adaptation_factors.values())
        }

# ============================================
# 🔮 CONFIDENCE PREDICTOR
# ============================================

class ConfidencePredictor:
    def __init__(self, horizon=8):
        self.horizon = horizon
        self.history = deque(maxlen=50)
        self.prediction_log = deque(maxlen=100)
        
    def predict(self, data):
        """Predict navigation confidence"""
        self.history.append(data)
        
        if len(self.history) < 5:
            return self._initial_prediction(data)
        
        return self._advanced_prediction(data)
    
    def _initial_prediction(self, data):
        """Initial prediction when data is insufficient"""
        return {
            "predicted_confidence": data['confidence'],
            "trend": "Collecting data",
            "trend_icon": "⏳",
            "trend_value": 0.0,
            "confidence_score": 0.3,
            "key_factors": ["Initial data collection"],
            "method": "initial",
            "horizon": self.horizon,
            "current_confidence": data['confidence'],
            "factors_impact": {
                "efield": 0.0,
                "temperature": 0.0,
                "wind": 0.0,
                "trend": 0.0
            }
        }
    
    def _advanced_prediction(self, data):
        """Advanced prediction using trend analysis"""
        recent = list(self.history)[-8:]
        confidences = [d['confidence'] for d in recent]
        
        # Trend analysis
        current_trend = 0.0
        if len(confidences) >= 2:
            try:
                x = list(range(len(confidences)))
                slope, _ = np.polyfit(x, confidences, 1)
                current_trend = slope
            except:
                current_trend = 0.0
        
        # Base prediction
        base_prediction = data['confidence']
        
        # Environmental factors impact
        efield_impact = max(-5, min(5, data['efield'] * -0.3))
        temp_impact = max(-3, min(3, (data['temperature'] + 25) * 0.1))
        wind_impact = max(-4, min(4, data['wind_speed'] * -0.15))
        
        # Trend impact
        trend_impact = current_trend * self.horizon * 0.8
        
        predicted = base_prediction + efield_impact + temp_impact + wind_impact + trend_impact
        predicted = max(65, min(98, round(predicted, 1)))
        
        # Determine trend
        if current_trend > 0.2:
            trend = "🚀 Improving"
            trend_icon = "↗️"
        elif current_trend > 0.05:
            trend = "📈 Slight improvement"
            trend_icon = "↗️"
        elif current_trend < -0.2:
            trend = "⚠️ Declining"
            trend_icon = "↘️"
        elif current_trend < -0.05:
            trend = "📉 Slight decline"
            trend_icon = "↘️"
        else:
            trend = "⚖️ Stable"
            trend_icon = "➡️"
        
        # Key factors
        key_factors = []
        if abs(data['efield']) > 3:
            key_factors.append(f"E-field ({data['efield']:.1f}V/m)")
        if data['temperature'] < -25:
            key_factors.append(f"Extreme cold ({data['temperature']:.1f}°C)")
        if data['wind_speed'] > 18:
            key_factors.append(f"Wind ({data['wind_speed']:.1f}km/h)")
        if abs(current_trend) > 0.15:
            key_factors.append(f"Strong trend ({current_trend:.2f}/cycle)")
        
        if not key_factors:
            key_factors = ["Stable conditions"]
        
        prediction = {
            "predicted_confidence": predicted,
            "current_confidence": data['confidence'],
            "trend": trend,
            "trend_icon": trend_icon,
            "trend_value": round(current_trend, 3),
            "confidence_score": min(0.9, 0.4 + len(self.history)/80),
            "key_factors": key_factors,
            "method": "trend_analysis",
            "horizon": self.horizon,
            "factors_impact": {
                "efield": round(efield_impact, 2),
                "temperature": round(temp_impact, 2),
                "wind": round(wind_impact, 2),
                "trend": round(trend_impact, 2)
            }
        }
        
        self.prediction_log.append(prediction)
        return prediction
    
    def get_prediction_stats(self):
        """Get prediction statistics"""
        if len(self.prediction_log) == 0:
            return {"total_predictions": 0}
        
        methods = {}
        for p in self.prediction_log:
            method = p.get('method', 'unknown')
            methods[method] = methods.get(method, 0) + 1
        
        return {
            "total_predictions": len(self.prediction_log),
            "methods_used": methods,
            "recent_confidence": self.prediction_log[-1]['confidence_score'] if self.prediction_log else 0
        }

# ============================================
# 🤖 NAVIGATION AI ENGINE
# ============================================

class PredictiveNavigationAI:
    def __init__(self):
        self.predictor = ConfidencePredictor()
        self.self_evaluator = AISelfEvaluator()
        self.pending_evaluations = deque(maxlen=20)
        self.decisions_log = []
        self.cycle_count = 0
        
        # Learn from decisions
        self.action_effectiveness = {
            "PROCEED_OPTIMAL": {"count": 0, "success_sum": 0},
            "PROCEED_CAUTIOUS": {"count": 0, "success_sum": 0},
            "REDUCE_SPEED": {"count": 0, "success_sum": 0},
            "HALT_AND_ASSESS": {"count": 0, "success_sum": 0}
        }
    
    def make_decision(self, data):
        """Make navigation decision with learning"""
        self.cycle_count += 1
        
        # Get prediction
        prediction = self.predictor.predict(data)
        
        # Base decision
        base_conf = data['confidence']
        pred_conf = prediction['predicted_confidence']
        
        # Use trend_value safely
        trend_value = prediction.get('trend_value', 0.0)
        
        # Decision with learning from experience
        action = self._learned_decision(base_conf, pred_conf, trend_value)
        
        # Assess risk
        risk_level = self._assess_risk(data, prediction)
        
        # Create decision
        decision = {
            "decision_id": f"DEC_{self.cycle_count:04d}",
            "timestamp": datetime.now().isoformat(),
            "cycle": self.cycle_count,
            "action": action,
            "current_confidence": base_conf,
            "predicted_confidence": pred_conf,
            "risk_level": risk_level,
            "prediction_details": prediction,
            "waiting_evaluation": True
        }
        
        self.decisions_log.append(decision)
        
        # Register for later evaluation
        self.pending_evaluations.append({
            "decision_id": decision["decision_id"],
            "prediction": prediction,
            "decision": decision,
            "data_at_decision": data.copy(),
            "timestamp": time.time()
        })
        
        # Update action effectiveness
        self.action_effectiveness[action]["count"] += 1
        
        return decision
    
    def _learned_decision(self, current, predicted, trend):
        """Learned decision from previous experiences"""
        
        # If trend is very strong
        if trend > 0.25:
            return "PROCEED_OPTIMAL"
        elif trend < -0.25:
            return "HALT_AND_ASSESS"
        
        # Normal decisions with learning
        if current > 88:
            return "PROCEED_OPTIMAL"
        elif current > 78:
            # Check this action's previous effectiveness
            cautious_stats = self.action_effectiveness["PROCEED_CAUTIOUS"]
            if cautious_stats["count"] > 0:
                avg_success = cautious_stats["success_sum"] / cautious_stats["count"]
                if avg_success > 0.7:
                    return "PROCEED_CAUTIOUS"
                else:
                    return "REDUCE_SPEED"  # Change strategy
            return "PROCEED_CAUTIOUS"
        elif current > 68:
            return "REDUCE_SPEED"
        else:
            return "HALT_AND_ASSESS"
    
    def _assess_risk(self, data, prediction):
        """Assess risk level"""
        risk_score = 0
        
        if data['confidence'] < 75:
            risk_score += 2
        elif data['confidence'] < 80:
            risk_score += 1
        
        if prediction['predicted_confidence'] < data['confidence'] - 5:
            risk_score += 2
        
        if abs(data['efield']) > 5:
            risk_score += 1
        if data['temperature'] < -28:
            risk_score += 1
        if data['wind_speed'] > 22:
            risk_score += 1
        
        if risk_score >= 4:
            return "high"
        elif risk_score >= 2:
            return "medium"
        else:
            return "low"
    
    def evaluate_past_predictions(self, current_data):
        """Evaluate past predictions"""
        now = time.time()
        evaluations_made = 0
        
        for item in list(self.pending_evaluations):
            # If 8 seconds have passed since decision
            if now - item["timestamp"] >= 8:
                evaluation = self.self_evaluator.evaluate_outcome(
                    item["prediction"], 
                    current_data
                )
                
                if evaluation:
                    # Update action effectiveness
                    decision = item["decision"]
                    action = decision["action"]
                    self.action_effectiveness[action]["success_sum"] += evaluation["success_score"]
                    
                    # Update decision with evaluation
                    for d in self.decisions_log:
                        if d["decision_id"] == decision["decision_id"]:
                            d["evaluation"] = evaluation
                            d["waiting_evaluation"] = False
                            break
                    
                    evaluations_made += 1
                
                self.pending_evaluations.remove(item)
        
        return evaluations_made
    
    def get_decision_stats(self):
        """Get decision statistics"""
        total = len(self.decisions_log)
        if total == 0:
            return {"total_decisions": 0}
        
        # Action distribution
        action_counts = {}
        risk_distribution = {}
        
        for d in self.decisions_log:
            action = d["action"]
            risk = d["risk_level"]
            
            action_counts[action] = action_counts.get(action, 0) + 1
            risk_distribution[risk] = risk_distribution.get(risk, 0) + 1
        
        # Action effectiveness
        action_effectiveness = {}
        for action, stats in self.action_effectiveness.items():
            if stats["count"] > 0:
                effectiveness = stats["success_sum"] / stats["count"]
                action_effectiveness[action] = {
                    "count": stats["count"],
                    "avg_success": round(effectiveness, 2)
                }
        
        return {
            "total_decisions": total,
            "pending_evaluations": len(self.pending_evaluations),
            "action_distribution": action_counts,
            "risk_distribution": risk_distribution,
            "action_effectiveness": action_effectiveness,
            "avg_confidence": round(sum(d["current_confidence"] for d in self.decisions_log) / total, 1)
        }

# ============================================
# 🚀 MAIN SYSTEM
# ============================================

class SnowDustAIComplete:
    def __init__(self, fast_mode=False):
        self.start_time = time.time()
        self.ai = PredictiveNavigationAI()
        self.data_history = []
        self.cycles = 0
        self.fast_mode = fast_mode
        self.report_manager = ReportManager()
        self.session_id = f"session_{int(time.time())}"
        
        print("\033c", end="")
        print("="*70)
        print("🤖 SNOW DUST AI COMPLETE - English Version")
        print("❄️  Self-Evaluating Predictive Navigation System")
        print("="*70)
        print()
    
    def generate_data(self):
        """Generate realistic navigation data"""
        t = time.time() - self.start_time
        
        # Variable electric field
        efield = math.sin(t * 0.5) * 3.0 + math.sin(t * 0.2) * 1.5 + random.uniform(-0.4, 0.4)
        
        # Base confidence with environmental effects
        base_confidence = 85
        field_effect = (1 - abs(efield) / 10) * 12  # Electric field effect
        
        wind_base = 15 + math.sin(t * 0.1) * 4 + math.sin(t * 0.3) * 2
        wind_speed = wind_base + random.uniform(-1.5, 1.5)
        wind_effect = -abs(wind_speed - 15) / 8  # Wind effect
        
        # Periodic confidence fluctuation
        cycle_effect = math.sin(t * 0.08) * 3
        
        # Random noise
        noise = random.uniform(-2, 2)
        
        confidence = base_confidence + field_effect + wind_effect + cycle_effect + noise
        confidence = max(68, min(96, round(confidence, 1)))
        
        # Temperature
        temp_variation = math.sin(t * 0.03) * 2.5 + math.sin(t * 0.15) * 1.0
        temperature = -27.5 + temp_variation + random.uniform(-0.3, 0.3)
        
        return {
            'timestamp': datetime.now().isoformat(),
            'cycle': self.cycles,
            'confidence': confidence,
            'efield': round(efield, 2),
            'temperature': round(temperature, 1),
            'wind_speed': round(wind_speed, 1),
            'time_elapsed': round(t, 1)
        }
    
    def display_status(self, data, decision, evaluations_made):
        """Display system status"""
        pred = decision['prediction_details']
        
        # Icons based on risk level
        risk_icons = {
            "low": "🟢",
            "medium": "🟡", 
            "high": "🔴"
        }
        
        # Colors based on confidence level
        if data['confidence'] >= 85:
            conf_color = "\033[92m"  # Green
        elif data['confidence'] >= 75:
            conf_color = "\033[93m"  # Yellow
        else:
            conf_color = "\033[91m"  # Red
        
        reset_color = "\033[0m"
        
        print(f"\r🔄 {self.cycles:04d} | ", end="")
        print(f"{risk_icons[decision['risk_level']]} {decision['action']:18} | ", end="")
        print(f"🎯 {conf_color}{data['confidence']:5.1f}%{reset_color} → {pred['predicted_confidence']:5.1f}% | ", end="")
        print(f"📊 {pred.get('trend_icon', '➡️')} {pred.get('trend', 'Analyzing')[:12]:12} | ", end="")
        print(f"📈 {evaluations_made:2d} evaluations", end="")
        
        sys.stdout.flush()
    
    def display_stats(self, stats):
        """Display system statistics"""
        print("\n" + "="*70)
        print("📊 SYSTEM STATISTICS")
        print("="*70)
        
        eval_stats = stats['evaluation']
        decision_stats = stats['decision']
        pred_stats = stats['prediction']
        learning_stats = stats['learning']
        
        print(f"\n🧠 SELF-EVALUATION:")
        print(f"   • Evaluations: {eval_stats.get('total_evaluations', 0)}")
        print(f"   • Avg error: {eval_stats.get('average_error', 0)}")
        print(f"   • Avg accuracy: {eval_stats.get('average_accuracy', 0)}%")
        
        print(f"\n🤖 DECISIONS:")
        print(f"   • Total: {decision_stats.get('total_decisions', 0)}")
        print(f"   • Pending: {decision_stats.get('pending_evaluations', 0)}")
        
        print(f"\n🔮 PREDICTIONS:")
        print(f"   • Total: {pred_stats.get('total_predictions', 0)}")
        
        print(f"\n📚 LEARNING:")
        print(f"   • Status: {learning_stats.get('status', 'Unknown')}")
        print(f"   • Confidence: {learning_stats.get('confidence', 0):.1%}")
        if learning_stats.get('adaptation_active', False):
            print(f"   • 🔄 Adaptation active")
        
        print(f"\n📊 PERFORMANCE:")
        print(f"   • Cycles: {stats['cycles']}")
        print(f"   • Runtime: {stats['runtime']}s")
        print(f"   • Session: {self.session_id}")
    
    def save_session_report(self, duration, avg_accuracy):
        """Save session report"""
        self.report_manager.add_session_record(
            "AI_NAVIGATION", 
            duration, 
            self.cycles, 
            avg_accuracy
        )
        
        # Update daily report
        stats = self.get_system_stats()
        self.report_manager.update_report(stats)
        
        # Save learning data
        learning_path = self.report_manager.save_learning_data(self, self.session_id)
        print(f"📚 Learning data saved: {learning_path}")
    
    def run(self, duration=60):
        """Run the system"""
        print("🚀 Starting system... (Ctrl+C to stop)")
        print(f"📁 Reports directory: {self.report_manager.daily_dir}")
        print(f"📅 Today's report: {self.report_manager.get_todays_report_path()}")
        print("-"*70)
        
        try:
            start = time.time()
            last_stat_display = start
            
            while time.time() - start < duration:
                # Generate data
                data = self.generate_data()
                self.data_history.append(data)
                
                # Make decision
                decision = self.ai.make_decision(data)
                
                # Evaluate past predictions
                evaluations_made = self.ai.evaluate_past_predictions(data)
                
                # Display status
                self.display_status(data, decision, evaluations_made)
                
                # Display stats every 10 seconds
                current_time = time.time()
                if current_time - last_stat_display > 10:
                    print("\n" + "-"*70)
                    stats = self.get_system_stats()
                    self.display_stats(stats)
                    self.report_manager.update_report(stats, data)
                    last_stat_display = current_time
                    print("-"*70)
                
                self.cycles += 1
                time.sleep(0.5 if not self.fast_mode else 0.2)
                
        except KeyboardInterrupt:
            print("\n\n⏹️  Stopped by user")
        
        self.summary()
    
    def get_system_stats(self):
        """Get system statistics"""
        return {
            "evaluation": self.ai.self_evaluator.get_evaluation_stats(),
            "decision": self.ai.get_decision_stats(),
            "prediction": self.ai.predictor.get_prediction_stats(),
            "learning": self.ai.self_evaluator.get_learning_progress(),
            "cycles": self.cycles,
            "runtime": round(time.time() - self.start_time, 1)
        }
    
    def summary(self):
        """Final summary"""
        stats = self.get_system_stats()
        duration = stats['runtime']
        avg_accuracy = stats['evaluation'].get('average_accuracy', 0)
        
        print("\n" + "="*70)
        print("🎯 FINAL SUMMARY - SNOW DUST AI COMPLETE")
        print("="*70)
        
        print(f"\n⏱️  Runtime: {duration} seconds")
        print(f"🔄 Total cycles: {self.cycles}")
        
        eval_stats = stats['evaluation']
        if eval_stats.get('total_evaluations', 0) > 0:
            print(f"\n🧠 AI PERFORMANCE:")
            print(f"   • Completed evaluations: {eval_stats.get('total_evaluations', 0)}")
            print(f"   • Average prediction accuracy: {eval_stats.get('average_accuracy', 0)}%")
            
            if eval_stats.get('success_distribution'):
                print(f"   • Success distribution:")
                for level, percentage in eval_stats['success_distribution'].items():
                    print(f"     - {level}: {percentage}")
        
        decision_stats = stats['decision']
        print(f"\n🤖 DECISION EFFECTIVENESS:")
        for action, eff in decision_stats.get('action_effectiveness', {}).items():
            if eff['count'] > 0:
                print(f"   • {action}: {eff['count']} times (success: {eff['avg_success']:.2f})")
        
        learning = stats['learning']
        print(f"\n📚 LEARNING PROGRESS:")
        print(f"   • {learning.get('status', 'Unknown')}")
        print(f"   • System confidence: {learning.get('confidence', 0):.1%}")
        
        # Save final reports
        self.save_session_report(duration, avg_accuracy)
        
        # Save daily report
        daily_report_path = self.report_manager.save_daily_report()
        if daily_report_path:
            print(f"\n📊 Daily report saved: {daily_report_path}")
        
        print("\n" + "="*70)
        print("✅ System completed successfully!")
        print(f"📁 All reports saved in: {self.report_manager.daily_dir}")
        print("="*70)

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

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='Snow Dust AI Complete System')
    parser.add_argument('--duration', type=int, default=60, help='Run duration in seconds')
    parser.add_argument('--fast', action='store_true', help='Fast mode')
    
    args = parser.parse_args()
    
    system = SnowDustAIComplete(fast_mode=args.fast)
    system.run(duration=args.duration)
