#!/usr/bin/env python3
"""
❄️ SNOW DUST AI EVOLVED - النسخة المصححة
"""

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

# ============================================
# 🧠 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):
        """تقييم نتيجة التنبؤ السابق"""
        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)
        
        # تحديد مستوى النجاح
        if absolute_error < 3:
            success_level = "ممتاز"
            success_score = 0.9
        elif absolute_error < 6:
            success_level = "جيد"
            success_score = 0.7
        elif absolute_error < 10:
            success_level = "مقبول"
            success_score = 0.5
        else:
            success_level = "ضعيف"
            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):
        """تعديل عوامل التعلم بناءً على التقييم"""
        error = evaluation['absolute_error']
        conditions = evaluation['conditions']
        
        if error > 5:
            # إذا كان الخطأ كبيراً، عدل الحساسيات
            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:
            # إذا كان التنبؤ دقيقاً، حافظ على الإعدادات
            pass
    
    def get_evaluation_stats(self):
        """الحصول على إحصائيات التقييم"""
        if not self.evaluation_log:
            return {
                "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_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):
        """تتبع تقدم التعلم"""
        if len(self.evaluation_log) < 5:
            return {"status": "جاري جمع البيانات", "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 = "تعلم ممتاز"
            confidence = 0.9
        elif avg_score > 0.6:
            status = "تعلم جيد"
            confidence = 0.7
        elif avg_score > 0.4:
            status = "تعلم مستمر"
            confidence = 0.5
        else:
            status = "بحاجة لتحسين"
            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):
        """تنبؤ بثقة الملاحة مع التعلم التكيفي"""
        self.history.append(data)
        
        if len(self.history) < 5:
            return self._initial_prediction(data)
        
        return self._advanced_prediction(data)
    
    def _initial_prediction(self, data):
        """تنبؤ أولي عند عدم وجود بيانات كافية"""
        return {
            "predicted_confidence": data['confidence'],
            "trend": "جاري جمع البيانات",
            "trend_icon": "⏳",
            "trend_value": 0.0,  # إضافة هذا المفتاح المفقود
            "confidence_score": 0.3,
            "key_factors": ["جمع البيانات الأولية"],
            "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):
        """تنبؤ متقدم باستخدام تحليل الاتجاه"""
        recent = list(self.history)[-8:]
        confidences = [d['confidence'] for d in recent]
        
        # تحليل الاتجاه
        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 = data['confidence']
        
        # تأثير العوامل البيئية
        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 = 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)))
        
        # تحديد الاتجاه
        if current_trend > 0.2:
            trend = "🚀 تحسن"
            trend_icon = "↗️"
        elif current_trend > 0.05:
            trend = "📈 تحسن طفيف"
            trend_icon = "↗️"
        elif current_trend < -0.2:
            trend = "⚠️ انخفاض"
            trend_icon = "↘️"
        elif current_trend < -0.05:
            trend = "📉 انخفاض طفيف"
            trend_icon = "↘️"
        else:
            trend = "⚖️ مستقر"
            trend_icon = "➡️"
        
        # العوامل الرئيسية
        key_factors = []
        if abs(data['efield']) > 3:
            key_factors.append(f"مجال كهربائي ({data['efield']:.1f}V/m)")
        if data['temperature'] < -25:
            key_factors.append(f"برد شديد ({data['temperature']:.1f}°C)")
        if data['wind_speed'] > 18:
            key_factors.append(f"رياح ({data['wind_speed']:.1f}km/h)")
        if abs(current_trend) > 0.15:
            key_factors.append(f"اتجاه قوي ({current_trend:.2f}/cycle)")
        
        if not key_factors:
            key_factors = ["ظروف مستقرة"]
        
        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):
        """إحصائيات التنبؤات"""
        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
        
        # تعلم من القرارات
        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):
        """اتخاذ قرار ملاحة مع التعلم"""
        self.cycle_count += 1
        
        # الحصول على التنبؤ
        prediction = self.predictor.predict(data)
        
        # اتخاذ القرار الأساسي
        base_conf = data['confidence']
        pred_conf = prediction['predicted_confidence']
        
        # استخدام trend_value بشكل آمن
        trend_value = prediction.get('trend_value', 0.0)
        
        # القرار مع التعلم من التجارب السابقة
        action = self._learned_decision(base_conf, pred_conf, trend_value)
        
        # تقييم المخاطر
        risk_level = self._assess_risk(data, prediction)
        
        # إنشاء القرار
        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)
        
        # تسجيل للتقيم لاحقاً
        self.pending_evaluations.append({
            "decision_id": decision["decision_id"],
            "prediction": prediction,
            "decision": decision,
            "data_at_decision": data.copy(),
            "timestamp": time.time()
        })
        
        # تحديث فعالية الإجراء
        self.action_effectiveness[action]["count"] += 1
        
        return decision
    
    def _learned_decision(self, current, predicted, trend):
        """قرار متعلم من التجارب السابقة"""
        
        # إذا كان الاتجاه قوياً جداً
        if trend > 0.25:
            return "PROCEED_OPTIMAL"
        elif trend < -0.25:
            return "HALT_AND_ASSESS"
        
        # قرارات عادية مع التعلم
        if current > 88:
            return "PROCEED_OPTIMAL"
        elif current > 78:
            # تحقق من فعالية هذا الإجراء سابقاً
            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"  # تغيير استراتيجية
            return "PROCEED_CAUTIOUS"
        elif current > 68:
            return "REDUCE_SPEED"
        else:
            return "HALT_AND_ASSESS"
    
    def _assess_risk(self, data, prediction):
        """تقييم مستوى المخاطرة"""
        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):
        """تقييم التنبؤات السابقة"""
        now = time.time()
        evaluations_made = 0
        
        for item in list(self.pending_evaluations):
            # إذا مر 8 ثواني على القرار
            if now - item["timestamp"] >= 8:
                evaluation = self.self_evaluator.evaluate_outcome(
                    item["prediction"], 
                    current_data
                )
                
                if evaluation:
                    # تحديث فعالية الإجراء
                    decision = item["decision"]
                    action = decision["action"]
                    self.action_effectiveness[action]["success_sum"] += evaluation["success_score"]
                    
                    # تحديث القرار بالتقييم
                    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):
        """إحصائيات القرارات"""
        total = len(self.decisions_log)
        if total == 0:
            return {"total_decisions": 0}
        
        # توزيع الإجراءات
        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 = {}
        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 SnowDustAIEvolved:
    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
        
        print("\033c", end="")
        print("="*70)
        print("🤖 SNOW DUST AI EVOLVED - النسخة المصححة")
        print("❄️  نظام ملاحة تنبؤي ذاتي التقييم")
        print("="*70)
        print()
    
    def generate_data(self):
        """توليد بيانات ملاحة واقعية"""
        t = time.time() - self.start_time
        
        # مجال كهربائي متغير
        efield = math.sin(t * 0.5) * 3.0 + math.sin(t * 0.2) * 1.5 + random.uniform(-0.4, 0.4)
        
        # ثقة أساسية مع تأثيرات بيئية
        base_confidence = 85
        field_effect = (1 - abs(efield) / 10) * 12  # تأثير المجال الكهربائي
        
        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  # تأثير الرياح
        
        # تذبذب دوري في الثقة
        cycle_effect = math.sin(t * 0.08) * 3
        
        # ضوضاء عشوائية
        noise = random.uniform(-2, 2)
        
        confidence = base_confidence + field_effect + wind_effect + cycle_effect + noise
        confidence = max(68, min(96, round(confidence, 1)))
        
        # درجة حرارة
        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):
        """عرض حالة النظام"""
        pred = decision['prediction_details']
        
        # رموز حسب مستوى المخاطرة
        risk_icons = {
            "low": "🟢",
            "medium": "🟡", 
            "high": "🔴"
        }
        
        # ألوان حسب مستوى الثقة
        if data['confidence'] >= 85:
            conf_color = "\033[92m"  # أخضر
        elif data['confidence'] >= 75:
            conf_color = "\033[93m"  # أصفر
        else:
            conf_color = "\033[91m"  # أحمر
        
        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', 'جاري تحليل')[:12]:12} | ", end="")
        print(f"📈 {evaluations_made:2d} تقييمات", end="")
        
        sys.stdout.flush()
    
    def display_stats(self, stats):
        """عرض الإحصائيات"""
        print("\n" + "="*70)
        print("📊 إحصائيات النظام")
        print("="*70)
        
        eval_stats = stats['evaluation']
        decision_stats = stats['decision']
        pred_stats = stats['prediction']
        learning_stats = stats['learning']
        
        print(f"\n🧠 التقييم الذاتي:")
        print(f"   • التقييمات: {eval_stats['total_evaluations']}")
        print(f"   • متوسط الخطأ: {eval_stats['average_error']}")
        print(f"   • متوسط الدقة: {eval_stats['average_accuracy']}%")
        
        print(f"\n🤖 القرارات:")
        print(f"   • القرارات: {decision_stats['total_decisions']}")
        print(f"   • المنتظرة: {decision_stats['pending_evaluations']}")
        
        print(f"\n🔮 التنبؤات:")
        print(f"   • عدد التنبؤات: {pred_stats['total_predictions']}")
        
        print(f"\n📚 التعلم:")
        print(f"   • حالة: {learning_stats['status']}")
        print(f"   • ثقة: {learning_stats['confidence']:.1%}")
        if learning_stats.get('adaptation_active', False):
            print(f"   • 🔄 التكيف نشط")
    
    def run(self, duration=60):
        """تشغيل النظام"""
        print("🚀 بدء التشغيل... (Ctrl+C للإيقاف)")
        print("-"*70)
        
        try:
            start = time.time()
            last_stat_display = start
            
            while time.time() - start < duration:
                # توليد البيانات
                data = self.generate_data()
                self.data_history.append(data)
                
                # اتخاذ القرار
                decision = self.ai.make_decision(data)
                
                # تقييم القرارات السابقة
                evaluations_made = self.ai.evaluate_past_predictions(data)
                
                # عرض الحالة
                self.display_status(data, decision, evaluations_made)
                
                # عرض الإحصائيات كل 10 ثواني
                current_time = time.time()
                if current_time - last_stat_display > 10:
                    print("\n" + "-"*70)
                    stats = self.get_system_stats()
                    self.display_stats(stats)
                    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⏹️  توقف بواسطة المستخدم")
        
        self.summary()
    
    def get_system_stats(self):
        """الحصول على إحصائيات النظام"""
        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):
        """ملخص نهائي"""
        stats = self.get_system_stats()
        
        print("\n" + "="*70)
        print("🎯 ملخص نهائي - SNOW DUST AI EVOLVED")
        print("="*70)
        
        print(f"\n⏱️  وقت التشغيل: {stats['runtime']} ثانية")
        print(f"🔄 عدد الدورات: {self.cycles}")
        
        eval_stats = stats['evaluation']
        if eval_stats['total_evaluations'] > 0:
            print(f"\n🧠 أداء الذكاء الاصطناعي:")
            print(f"   • التقييمات المكتملة: {eval_stats['total_evaluations']}")
            print(f"   • متوسط دقة التنبؤ: {eval_stats['average_accuracy']}%")
        
        decision_stats = stats['decision']
        print(f"\n🤖 فعالية القرارات:")
        for action, eff in decision_stats.get('action_effectiveness', {}).items():
            if eff['count'] > 0:
                print(f"   • {action}: {eff['count']} مرة (نجاح: {eff['avg_success']:.2f})")
        
        learning = stats['learning']
        print(f"\n📚 تقدم التعلم:")
        print(f"   • {learning['status']}")
        print(f"   • ثقة النظام: {learning['confidence']:.1%}")
        
        print("\n" + "="*70)
        print("✅ النظام الآن يعمل بشكل صحيح ويتعلم من قراراته!")
        print("="*70)

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

if __name__ == "__main__":
    import argparse
    
    parser = argparse.ArgumentParser(description='Snow Dust AI Evolved System')
    parser.add_argument('--duration', type=int, default=60, help='مدة التشغيل بالثواني')
    parser.add_argument('--fast', action='store_true', help='وضع سريع')
    
    args = parser.parse_args()
    
    system = SnowDustAIEvolved(fast_mode=args.fast)
    system.run(duration=args.duration)
