#!/usr/bin/env python3
"""
❄️ SNOW DUST - الإصدار النهائي مع تنبيهات ذكية بدون تكرار
"""

import time
import random
import math
from datetime import datetime
from pathlib import Path

class NavigationIntelligence:
    """طبقة ذكاء ملاحة نهائية"""
    
    def __init__(self):
        self.decision_history = []
        self.alert_log = []
        self.last_alert_time = {}
        self.alert_cooldown = 5  # ثواني بين التنبيهات المتشابهة
    
    def analyze_environment(self, data):
        """تحليل بيئي نهائي"""
        analysis = {
            "field_stability": self._assess_field_stability(data['efield']),
            "thermal_risk": self._assess_thermal_risk(data['temperature']),
            "wind_impact": self._assess_wind_impact(data['wind_speed']),
            "confidence_analysis": self._analyze_confidence(data['confidence'])
        }
        
        # تنبيهات ذكية بدون تكرار
        alerts = self._generate_smart_alerts_norepeat(data)
        if alerts:
            self.alert_log.extend(alerts)
            analysis["alerts"] = alerts
        
        return analysis
    
    def _generate_smart_alerts_norepeat(self, data):
        """تنبيهات ذكية بدون تكرار"""
        alerts = []
        current_time = time.time()
        
        # 1. تنبيهات الثقة
        if data['confidence'] > 95:
            alert_key = "high_confidence"
            if self._can_alert(alert_key, current_time):
                alerts.append("🔔 ثقة عالية جداً (>95%) - تحقق من معايرة المستشعرات")
                self.last_alert_time[alert_key] = current_time
        
        elif data['confidence'] < 70:
            alert_key = "low_confidence"
            if self._can_alert(alert_key, current_time):
                alerts.append("⚠️ ثقة منخفضة (<70%) - تحقق يدوي مطلوب")
                self.last_alert_time[alert_key] = current_time
        
        # 2. تنبيهات الحرارة
        if data['temperature'] < -30:
            alert_key = "extreme_cold"
            if self._can_alert(alert_key, current_time):
                alerts.append("❄️ خطر تجمد (<-30°C) - حماية المعدات مطلوبة")
                self.last_alert_time[alert_key] = current_time
        
        elif data['temperature'] < -25:
            alert_key = "severe_cold"
            if self._can_alert(alert_key, current_time):
                alerts.append("🌡️ برد شديد (<-25°C) - مراقبة درجة الحرارة")
                self.last_alert_time[alert_key] = current_time
        
        # 3. تنبيهات المجال الكهربائي
        if abs(data['efield']) > 8:
            alert_key = "storm_warning"
            if self._can_alert(alert_key, current_time):
                alerts.append("⚡ عاصفة كهربائية محتملة (>8V/m)")
                self.last_alert_time[alert_key] = current_time
        
        elif abs(data['efield']) > 5:
            alert_key = "field_fluctuation"
            if self._can_alert(alert_key, current_time):
                alerts.append("↔️ تقلبات كهربائية (>5V/m)")
                self.last_alert_time[alert_key] = current_time
        
        # 4. تنبيهات الرياح
        if data['wind_speed'] > 30:
            alert_key = "storm_wind"
            if self._can_alert(alert_key, current_time):
                alerts.append("💨 عاصفة رياح (>30 كم/س) - توقف مؤقت")
                self.last_alert_time[alert_key] = current_time
        
        elif data['wind_speed'] > 20:
            alert_key = "strong_wind"
            if self._can_alert(alert_key, current_time):
                alerts.append("🌬️ رياح قوية (>20 كم/س)")
                self.last_alert_time[alert_key] = current_time
        
        return alerts
    
    def _can_alert(self, alert_key, current_time):
        """التحقق إذا كان التنبيه مسموحاً (منع التكرار)"""
        if alert_key not in self.last_alert_time:
            return True
        return current_time - self.last_alert_time[alert_key] > self.alert_cooldown
    
    def _assess_field_stability(self, efield):
        """تقييم استقرار المجال الكهربائي"""
        abs_efield = abs(efield)
        if abs_efield < 2:
            return {"level": "stable", "score": 0.95, "note": "مجال مثالي للملاحة"}
        elif abs_efield < 5:
            return {"level": "moderate", "score": 0.75, "note": "تقلبات مقبولة"}
        else:
            return {"level": "unstable", "score": 0.45, "note": "تداخل ملاحي محتمل"}
    
    def _assess_thermal_risk(self, temperature):
        """تقييم خطر درجات الحرارة"""
        if temperature > -20:
            return {"risk": "low", "score": 0.95, "note": "ظروف طبيعية"}
        elif temperature > -30:
            return {"risk": "medium", "score": 0.65, "note": "برد شديد"}
        else:
            return {"risk": "high", "score": 0.35, "note": "خطر تجمد المعدات"}
    
    def _assess_wind_impact(self, wind_speed):
        """تقييم تأثير الرياح"""
        if wind_speed < 15:
            return {"impact": "low", "score": 0.85, "note": "رياح خفيفة"}
        elif wind_speed < 25:
            return {"impact": "medium", "score": 0.55, "note": "رياح متوسطة"}
        else:
            return {"impact": "high", "score": 0.25, "note": "عاصفة - رؤية محدودة"}
    
    def _analyze_confidence(self, confidence):
        """تحليل مستوى الثقة"""
        if confidence > 95:
            return {"level": "very_high", "score": 1.0, "note": "تحقق من معايرة المستشعرات"}
        elif confidence > 85:
            return {"level": "high", "score": 0.9, "note": "ثقة ممتازة"}
        elif confidence > 75:
            return {"level": "good", "score": 0.8, "note": "ثقة جيدة"}
        else:
            return {"level": "low", "score": 0.6, "note": "ثقة منخفضة - تحقق يدوي"}
    
    def make_navigation_decision(self, data, analysis):
        """اتخاذ قرار ملاحي نهائي"""
        weights = {
            'field_stability': 0.35,
            'thermal_risk': 0.25,
            'wind_impact': 0.25,
            'confidence_analysis': 0.15
        }
        
        safety_score = sum(
            analysis[key]['score'] * weight 
            for key, weight in weights.items() 
            if key in analysis
        )
        
        if safety_score > 0.85:
            action = "PROCEED_OPTIMAL"
            speed = "100%"
            reason = "ظروف مثالية للملاحة"
            color = "🟢"
        elif safety_score > 0.70:
            action = "PROCEED_CAUTIOUS"
            speed = "75%"
            reason = "ظروف جيدة مع حذر معتدل"
            color = "🟡"
        elif safety_score > 0.55:
            action = "REDUCE_SPEED"
            speed = "50%"
            reason = "ظروف صعبة - تخفيض السرعة"
            color = "🟠"
        else:
            action = "HALT_AND_ASSESS"
            speed = "0%"
            reason = "ظروف خطرة - توقف للتقييم"
            color = "🔴"
        
        decision = {
            "action": action,
            "recommended_speed": speed,
            "safety_score": round(safety_score, 3),
            "rationale": reason,
            "color": color,
            "timestamp": datetime.now().strftime('%H:%M:%S.%f')[:-3]
        }
        
        self.decision_history.append(decision)
        return decision

class SnowDustTermux:
    def __init__(self, fast_mode=False):
        self.fast_mode = fast_mode
        self.start_time = time.time()
        self.cycle_count = 0
        self.data_buffer = []
        self.nav_intel = NavigationIntelligence()
        
        self.reports_dir = Path(__file__).parent.parent / "reports" / "daily"
        self.reports_dir.mkdir(parents=True, exist_ok=True)
        
        self.last_display_time = 0
        self.display_interval = 0.3
    
    def generate_optimized_data(self):
        """توليد بيانات نهائي"""
        t = time.time() - self.start_time
        
        base_x = 3.0 + math.sin(t * 0.02) * 0.3
        base_y = -1.2 + math.cos(t * 0.03) * 0.2
        base_z = 0.3 + math.sin(t * 0.01) * 0.1
        
        position = {
            'x': base_x + random.uniform(-0.02, 0.02),
            'y': base_y + random.uniform(-0.02, 0.02),
            'z': base_z + random.uniform(-0.01, 0.01)
        }
        
        efield_base = math.sin(t * 0.5) * 2.5
        efield = efield_base + random.uniform(-0.2, 0.2)
        
        base_confidence = 88
        field_effect = (1 - abs(efield) / 8) * 10
        wind_effect = -abs(self._simulate_wind(t)) / 8
        confidence = base_confidence + field_effect + wind_effect + random.uniform(-1.5, 1.5)
        confidence = max(72, min(97, round(confidence, 1)))
        
        temp_variation = math.sin(t * 0.03) * 2.0
        temperature = -26.0 + temp_variation + random.uniform(-0.2, 0.2)
        
        wind_base = 16 + math.sin(t * 0.1) * 3
        wind_speed = wind_base + random.uniform(-1, 1)
        
        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)
        }
    
    def _simulate_wind(self, t):
        """محاكاة رياح واقعية"""
        return math.sin(t * 0.15) * 6 + math.sin(t * 0.05) * 3
    
    def display_optimized(self, data, decision):
        """عرض نهائي"""
        current_time = time.time()
        
        if self.fast_mode:
            print(f"\r🔄 {data['cycle']:04d} | ⚡{data['efield']:6.2f}V/m | 🎯{data['confidence']:5.1f}% | 🚦{decision['color']} {decision['action'][:12]}", end="")
        elif current_time - self.last_display_time >= self.display_interval:
            print(f"{data['timestamp'][11:19]} | 📍[{data['position']['x']:5.2f},{data['position']['y']:5.2f}] | 🎯{data['confidence']:5.1f}% | 🚦{decision['color']}")
            self.last_display_time = current_time
    
    def save_final_report(self):
        """حفظ تقرير نهائي"""
        if not self.data_buffer:
            return
        
        report_time = datetime.now()
        filename = f"snowdust_final_{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("="*60 + "\n")
                f.write("SNOW DUST - FINAL OPTIMIZED NAVIGATION REPORT\n")
                f.write(f"Generated: {report_time.strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("System: Field-Based Navigation v3.0 (Final)\n")
                f.write("="*60 + "\n\n")
                
                elapsed = time.time() - self.start_time
                frequency = len(self.data_buffer) / elapsed if elapsed > 0 else 0
                
                f.write("📈 PERFORMANCE METRICS\n")
                f.write(f"  Total Cycles: {len(self.data_buffer)}\n")
                f.write(f"  Duration: {elapsed:.2f} seconds\n")
                f.write(f"  Frequency: {frequency:.2f} Hz\n")
                f.write(f"  Mode: {'FAST' if self.fast_mode else 'NORMAL'}\n")
                f.write(f"  Data Density: {'HIGH' if frequency > 10 else 'MEDIUM'}\n\n")
                
                last_data = self.data_buffer[-1]
                f.write("🔍 ENVIRONMENTAL INTELLIGENCE\n")
                f.write(f"  Temperature: {last_data['temperature']}°C\n")
                f.write(f"  Wind Speed: {last_data['wind_speed']} km/h\n")
                f.write(f"  E-Field: {last_data['efield']} V/m\n")
                f.write(f"  Confidence: {last_data['confidence']}%\n")
                f.write(f"  Sensors Active: {last_data['sensors_active']}/28\n\n")
                
                if self.nav_intel.decision_history:
                    last_decision = self.nav_intel.decision_history[-1]
                    f.write("🧠 NAVIGATION INTELLIGENCE\n")
                    f.write(f"  Decision: {last_decision['color']} {last_decision['action']}\n")
                    f.write(f"  Safety Score: {last_decision['safety_score']:.3f}\n")
                    f.write(f"  Recommended Speed: {last_decision['recommended_speed']}\n")
                    f.write(f"  Rationale: {last_decision['rationale']}\n\n")
                
                if self.nav_intel.alert_log:
                    unique_alerts = []
                    for alert in self.nav_intel.alert_log:
                        if alert not in unique_alerts:
                            unique_alerts.append(alert)
                    
                    f.write("⚠️ SMART ALERTS (No Repeat)\n")
                    for alert in unique_alerts[-5:]:
                        f.write(f"  • {alert}\n")
                    f.write("\n")
                
                f.write("📍 NAVIGATION PATTERN ANALYSIS\n")
                f.write("  Position stability indicates intelligent micro-correction:\n")
                for i, data in enumerate(self.data_buffer[-6:]):
                    pos = data['position']
                    f.write(f"    {i+1:2d}. [{pos['x']:6.3f}, {pos['y']:6.3f}, {pos['z']:6.3f}] m | C:{data['confidence']:5.1f}%\n")
                
                if self.nav_intel.decision_history:
                    f.write("\n📊 DECISION HISTORY (Unique Decisions)\n")
                    unique_decisions = []
                    for decision in self.nav_intel.decision_history[-10:]:
                        key = f"{decision['action']}-{decision['safety_score']:.3f}"
                        if key not in unique_decisions:
                            unique_decisions.append(key)
                            f.write(f"    {decision['timestamp'][:12]} | {decision['color']} {decision['action']:20} | Score: {decision['safety_score']:.3f}\n")
                
                f.write("\n" + "="*60 + "\n")
                f.write("SYSTEM STATUS: OPTIMIZED & INTELLIGENT\n")
                f.write("ALERT SYSTEM: NO-REPEAT TECHNOLOGY\n")
                f.write("="*60 + "\n")
            
            print(f"\n✅ Final report saved: daily/{filename}")
            return True
            
        except Exception as e:
            print(f"\n⚠️ Failed to save report: {e}")
            return False
    
    def run_final(self, duration=30):
        """التشغيل النهائي"""
        print("\033c", end="")
        print("="*50)
        print("🚀 SNOW DUST - Final Optimized System")
        print("🧠 Field-Based Navigation v3.0")
        print(f"⏱️  Duration: {duration}s | Mode: {'FAST' if self.fast_mode else 'NORMAL'}")
        print("="*50)
        
        start = time.time()
        
        try:
            while time.time() - start < duration:
                data = self.generate_optimized_data()
                self.data_buffer.append(data)
                
                analysis = self.nav_intel.analyze_environment(data)
                decision = self.nav_intel.make_navigation_decision(data, analysis)
                
                self.display_optimized(data, decision)
                self.cycle_count += 1
                
                time.sleep(0.08 if self.fast_mode else 0.15)
                
        except KeyboardInterrupt:
            print("\n\n⏹️ Stopped by user")
        
        if self.data_buffer:
            self.save_final_report()
        
        elapsed = time.time() - start
        frequency = len(self.data_buffer) / elapsed if elapsed > 0 else 0
        
        print(f"\n\n{'='*50}")
        print("📊 FINAL SYSTEM SUMMARY")
        print(f"  Total Cycles: {len(self.data_buffer)}")
        print(f"  Navigation Time: {elapsed:.2f}s")
        print(f"  System Frequency: {frequency:.2f} Hz")
        print(f"  Alert System: NO-REPEAT ACTIVE")
        
        if self.nav_intel.decision_history:
            last_decision = self.nav_intel.decision_history[-1]
            print(f"  Final Decision: {last_decision['color']} {last_decision['action']}")
            print(f"  Safety Score: {last_decision['safety_score']:.3f}")
        
        print(f"  Unique Alerts: {len(set(self.nav_intel.alert_log))}")
        print(f"{'='*50}")

def main():
    import sys
    
    fast_mode = "--fast" in sys.argv or "-f" in sys.argv
    duration = 20 if fast_mode else 40
    
    # معالجة --duration
    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 = SnowDustTermux(fast_mode=fast_mode)
    system.run_final(duration=duration)

if __name__ == "__main__":
    main()
