#!/usr/bin/env python3
"""
❄️ SNOW DUST - Final Navigation Intelligence System
Self-learning AI with TXT reports only
"""

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

# ============================================
# 📁 TXT Report Manager
# ============================================

class ReportManager:
    """Manages daily reports in TXT format only"""
    
    def __init__(self, base_dir="../reports"):
        self.base_dir = Path(base_dir)
        self.daily_dir = self.base_dir / "daily"
        
        # Create directories
        for directory in [self.base_dir, self.daily_dir]:
            directory.mkdir(parents=True, exist_ok=True)
        
        self.current_date = datetime.now().strftime("%Y-%m-%d")
        self.session_id = datetime.now().strftime("%Y%m%d_%H%M%S")
        self.daily_log = []
        self.session_counter = 0
    
    def add_session(self, session_data):
        """Add session data to daily log"""
        self.session_counter += 1
        log_entry = {
            "session_id": self.session_id,
            "session_number": self.session_counter,
            "timestamp": datetime.now().isoformat(),
            "duration_seconds": session_data.get("duration", 0),
            "total_cycles": session_data.get("cycles", 0),
            "total_decisions": session_data.get("decisions", 0),
            "average_accuracy": session_data.get("accuracy", 0),
            "ai_confidence": session_data.get("ai_confidence", 0)
        }
        
        self.daily_log.append(log_entry)
        return log_entry
    
    def save_session_report(self, session_stats, ai_data):
        """Save individual session report as TXT"""
        filename = f"session_{self.session_id}.txt"
        filepath = self.daily_dir / filename
        
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                # Header
                f.write("="*60 + "\n")
                f.write("SNOW DUST - SESSION REPORT\n")
                f.write(f"Session ID: {self.session_id}\n")
                f.write(f"Date: {self.current_date}\n")
                f.write(f"Time: {datetime.now().strftime('%H:%M:%S')}\n")
                f.write("="*60 + "\n\n")
                
                # Session Statistics
                f.write("SESSION STATISTICS\n")
                f.write("-"*40 + "\n")
                f.write(f"Duration: {session_stats.get('duration', 0):.1f} seconds\n")
                f.write(f"Total Cycles: {session_stats.get('cycles', 0)}\n")
                f.write(f"Total Decisions: {session_stats.get('decisions', 0)}\n")
                f.write(f"Evaluations Made: {session_stats.get('evaluations', 0)}\n")
                f.write(f"Average Accuracy: {session_stats.get('accuracy', 0):.1f}%\n")
                f.write(f"AI Confidence: {session_stats.get('ai_confidence', 0):.1%}\n\n")
                
                # Navigation Data
                if ai_data:
                    f.write("NAVIGATION INTELLIGENCE\n")
                    f.write("-"*40 + "\n")
                    f.write(f"Current Position: {ai_data.get('position', 'N/A')}\n")
                    f.write(f"Confidence Level: {ai_data.get('confidence', 0)}%\n")
                    f.write(f"Electric Field: {ai_data.get('efield', 0)} V/m\n")
                    f.write(f"Temperature: {ai_data.get('temperature', 0)}°C\n")
                    f.write(f"Wind Speed: {ai_data.get('wind_speed', 0)} km/h\n\n")
                
                # Decision Analysis
                if session_stats.get('decision_types'):
                    f.write("DECISION ANALYSIS\n")
                    f.write("-"*40 + "\n")
                    for action, count in session_stats['decision_types'].items():
                        f.write(f"{action}: {count} times\n")
                    f.write("\n")
                
                # System Status
                f.write("SYSTEM STATUS\n")
                f.write("-"*40 + "\n")
                f.write("Report Format: TXT\n")
                f.write("Data Storage: Active\n")
                f.write("Learning Mode: Enabled\n")
                f.write("Navigation: Operational\n")
                
                # Footer
                f.write("\n" + "="*60 + "\n")
                f.write("END OF SESSION REPORT\n")
                f.write("="*60 + "\n")
            
            print(f"📄 Session report saved: daily/{filename}")
            return filepath
            
        except Exception as e:
            print(f"⚠️ Failed to save session report: {e}")
            return None
    
    def save_daily_summary(self):
        """Save daily summary report as TXT"""
        if not self.daily_log:
            return None
        
        filename = f"daily_summary_{self.current_date}.txt"
        filepath = self.daily_dir / filename
        
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                # Header
                f.write("="*60 + "\n")
                f.write("SNOW DUST - DAILY SUMMARY REPORT\n")
                f.write(f"Date: {self.current_date}\n")
                f.write(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                f.write("="*60 + "\n\n")
                
                # Daily Totals
                total_sessions = len(self.daily_log)
                total_duration = sum(log.get("duration_seconds", 0) for log in self.daily_log)
                total_cycles = sum(log.get("total_cycles", 0) for log in self.daily_log)
                total_decisions = sum(log.get("total_decisions", 0) for log in self.daily_log)
                avg_accuracy = sum(log.get("average_accuracy", 0) for log in self.daily_log) / total_sessions if total_sessions > 0 else 0
                avg_confidence = sum(log.get("ai_confidence", 0) for log in self.daily_log) / total_sessions if total_sessions > 0 else 0
                
                f.write("DAILY TOTALS\n")
                f.write("-"*40 + "\n")
                f.write(f"Total Sessions: {total_sessions}\n")
                f.write(f"Total Duration: {total_duration} seconds ({total_duration/3600:.2f} hours)\n")
                f.write(f"Total Cycles: {total_cycles}\n")
                f.write(f"Total Decisions: {total_decisions}\n")
                f.write(f"Average Accuracy: {avg_accuracy:.1f}%\n")
                f.write(f"Average AI Confidence: {avg_confidence:.1%}\n\n")
                
                # Session Details
                f.write("SESSION DETAILS\n")
                f.write("-"*40 + "\n")
                for i, log in enumerate(self.daily_log, 1):
                    f.write(f"Session {i}: {log.get('session_id', 'N/A')}\n")
                    f.write(f"  Time: {log.get('timestamp', 'N/A')}\n")
                    f.write(f"  Duration: {log.get('duration_seconds', 0)} seconds\n")
                    f.write(f"  Cycles: {log.get('total_cycles', 0)}\n")
                    f.write(f"  Accuracy: {log.get('average_accuracy', 0)}%\n")
                    f.write(f"  AI Confidence: {log.get('ai_confidence', 0):.1%}\n\n")
                
                # Performance Analysis
                f.write("PERFORMANCE ANALYSIS\n")
                f.write("-"*40 + "\n")
                if avg_accuracy > 85:
                    f.write("Performance: EXCELLENT\n")
                    f.write("AI is learning effectively\n")
                elif avg_accuracy > 70:
                    f.write("Performance: GOOD\n")
                    f.write("System is operating well\n")
                elif avg_accuracy > 50:
                    f.write("Performance: FAIR\n")
                    f.write("Some improvements needed\n")
                else:
                    f.write("Performance: NEEDS ATTENTION\n")
                    f.write("Manual review recommended\n")
                
                if total_cycles > 5000:
                    f.write("System Usage: HIGH\n")
                elif total_cycles > 1000:
                    f.write("System Usage: MODERATE\n")
                else:
                    f.write("System Usage: LOW\n")
                
                # Recommendations
                f.write("\nRECOMMENDATIONS\n")
                f.write("-"*40 + "\n")
                if avg_accuracy < 60:
                    f.write("1. Review sensor calibration\n")
                    f.write("2. Check environmental conditions\n")
                    f.write("3. Consider system maintenance\n")
                else:
                    f.write("1. Continue normal operations\n")
                    f.write("2. Monitor system performance\n")
                    f.write("3. Regular data backup recommended\n")
                
                # Footer
                f.write("\n" + "="*60 + "\n")
                f.write("END OF DAILY SUMMARY\n")
                f.write("="*60 + "\n")
            
            print(f"📊 Daily summary saved: daily/{filename}")
            return filepath
            
        except Exception as e:
            print(f"⚠️ Failed to save daily summary: {e}")
            return None

# ============================================
# 🧠 AI Navigation Intelligence
# ============================================

class NavigationAI:
    """AI navigation system with self-learning"""
    
    def __init__(self):
        self.decision_history = deque(maxlen=100)
        self.prediction_log = deque(maxlen=50)
        self.evaluation_log = deque(maxlen=50)
        self.learning_memory = deque(maxlen=200)
        
        # Learning parameters
        self.confidence_threshold = 75
        self.risk_tolerance = 0.7
        self.learning_rate = 0.1
        
        # Statistics
        self.total_decisions = 0
        self.successful_predictions = 0
        self.average_error = 0
    
    def analyze_environment(self, sensor_data):
        """Analyze current environment"""
        analysis = {
            "field_analysis": self._analyze_electric_field(sensor_data['efield']),
            "thermal_analysis": self._analyze_temperature(sensor_data['temperature']),
            "wind_analysis": self._analyze_wind(sensor_data['wind_speed']),
            "confidence_analysis": self._analyze_confidence(sensor_data['confidence'])
        }
        
        # Calculate overall safety score
        weights = [0.35, 0.25, 0.25, 0.15]
        scores = [analysis[key]['score'] for key in analysis.keys()]
        safety_score = sum(score * weight for score, weight in zip(scores, weights))
        
        analysis["safety_score"] = round(safety_score, 3)
        analysis["timestamp"] = datetime.now().isoformat()
        
        return analysis
    
    def _analyze_electric_field(self, efield):
        """Analyze electric field stability"""
        abs_field = abs(efield)
        if abs_field < 2:
            return {"status": "stable", "score": 0.95, "note": "Ideal for navigation"}
        elif abs_field < 5:
            return {"status": "moderate", "score": 0.75, "note": "Acceptable fluctuations"}
        else:
            return {"status": "unstable", "score": 0.45, "note": "Potential interference"}
    
    def _analyze_temperature(self, temperature):
        """Analyze temperature conditions"""
        if temperature > -20:
            return {"status": "normal", "score": 0.95, "note": "Normal conditions"}
        elif temperature > -30:
            return {"status": "cold", "score": 0.65, "note": "Severe cold"}
        else:
            return {"status": "extreme", "score": 0.35, "note": "Risk of equipment freeze"}
    
    def _analyze_wind(self, wind_speed):
        """Analyze wind conditions"""
        if wind_speed < 15:
            return {"status": "calm", "score": 0.85, "note": "Light wind"}
        elif wind_speed < 25:
            return {"status": "moderate", "score": 0.55, "note": "Moderate wind"}
        else:
            return {"status": "storm", "score": 0.25, "note": "Storm conditions"}
    
    def _analyze_confidence(self, confidence):
        """Analyze navigation confidence"""
        if confidence > 90:
            return {"level": "very_high", "score": 0.95, "note": "Excellent confidence"}
        elif confidence > 80:
            return {"level": "high", "score": 0.85, "note": "Good confidence"}
        elif confidence > 70:
            return {"level": "medium", "score": 0.70, "note": "Moderate confidence"}
        else:
            return {"level": "low", "score": 0.55, "note": "Low confidence"}
    
    def make_decision(self, sensor_data, analysis):
        """Make navigation decision"""
        self.total_decisions += 1
        
        safety_score = analysis["safety_score"]
        confidence = sensor_data['confidence']
        
        # Smart decision making with learning
        if safety_score > 0.85 and confidence > 85:
            action = "PROCEED_OPTIMAL"
            speed = "100%"
            reason = "Optimal conditions"
            color = "🟢"
        elif safety_score > 0.70 and confidence > 75:
            action = "PROCEED_CAUTIOUS"
            speed = "75%"
            reason = "Good conditions with caution"
            color = "🟡"
        elif safety_score > 0.55:
            action = "REDUCE_SPEED"
            speed = "50%"
            reason = "Challenging conditions"
            color = "🟠"
        else:
            action = "HALT_AND_ASSESS"
            speed = "0%"
            reason = "High risk - assessment needed"
            color = "🔴"
        
        decision = {
            "id": f"DEC_{self.total_decisions:04d}",
            "timestamp": datetime.now().isoformat(),
            "action": action,
            "speed": speed,
            "reason": reason,
            "color": color,
            "safety_score": safety_score,
            "confidence": confidence,
            "analysis": analysis
        }
        
        self.decision_history.append(decision)
        return decision
    
    def predict_confidence(self, current_data, history_length=8):
        """Predict future confidence"""
        if len(self.prediction_log) < history_length:
            return {
                "predicted_confidence": current_data['confidence'],
                "trend": "collecting_data",
                "confidence_score": 0.3
            }
        
        # Simple trend analysis
        recent_confidences = [data['confidence'] for data in list(self.prediction_log)[-history_length:]]
        if len(recent_confidences) >= 3:
            try:
                x = list(range(len(recent_confidences)))
                slope, intercept = np.polyfit(x, recent_confidences, 1)
                
                predicted = current_data['confidence'] + (slope * 5)  # 5 cycles ahead
                predicted = max(65, min(98, round(predicted, 1)))
                
                if slope > 0.1:
                    trend = "improving"
                elif slope < -0.1:
                    trend = "declining"
                else:
                    trend = "stable"
                    
                return {
                    "predicted_confidence": predicted,
                    "trend": trend,
                    "confidence_score": min(0.9, 0.5 + abs(slope) * 2),
                    "slope": round(slope, 3)
                }
            except:
                pass
        
        return {
            "predicted_confidence": current_data['confidence'],
            "trend": "stable",
            "confidence_score": 0.5
        }
    
    def evaluate_prediction(self, prediction, actual_data):
        """Evaluate prediction accuracy"""
        predicted = prediction.get("predicted_confidence", 0)
        actual = actual_data.get("confidence", 0)
        
        error = abs(actual - predicted)
        accuracy = max(0, 100 - error * 5)
        
        evaluation = {
            "timestamp": datetime.now().isoformat(),
            "predicted": predicted,
            "actual": actual,
            "error": round(error, 2),
            "accuracy": round(accuracy, 1),
            "successful": error < 5
        }
        
        self.evaluation_log.append(evaluation)
        
        if error < 5:
            self.successful_predictions += 1
        
        # Update average error
        total_errors = self.average_error * (len(self.evaluation_log) - 1)
        self.average_error = (total_errors + error) / len(self.evaluation_log)
        
        # Learn from evaluation
        if error > 8:
            self.confidence_threshold = max(70, self.confidence_threshold - 1)
        elif error < 2 and len(self.evaluation_log) > 10:
            self.confidence_threshold = min(85, self.confidence_threshold + 0.5)
        
        return evaluation
    
    def get_ai_stats(self):
        """Get AI statistics"""
        total_evals = len(self.evaluation_log)
        success_rate = (self.successful_predictions / total_evals * 100) if total_evals > 0 else 0
        
        return {
            "total_decisions": self.total_decisions,
            "total_evaluations": total_evals,
            "successful_predictions": self.successful_predictions,
            "success_rate": round(success_rate, 1),
            "average_error": round(self.average_error, 2),
            "confidence_threshold": self.confidence_threshold,
            "learning_active": total_evals > 5,
            "decision_types": self._count_decision_types()
        }
    
    def _count_decision_types(self):
        """Count types of decisions made"""
        types = {}
        for decision in self.decision_history:
            action = decision.get("action", "UNKNOWN")
            types[action] = types.get(action, 0) + 1
        return types

# ============================================
# 🚀 Main System
# ============================================

class SnowDustSystem:
    """Main Snow Dust Navigation System"""
    
    def __init__(self, fast_mode=False):
        self.start_time = time.time()
        self.fast_mode = fast_mode
        self.cycle_count = 0
        self.data_buffer = deque(maxlen=100)
        
        self.ai = NavigationAI()
        self.report_manager = ReportManager()
        
        # Session statistics
        self.session_stats = {
            "duration": 0,
            "cycles": 0,
            "decisions": 0,
            "evaluations": 0,
            "accuracy": 0,
            "ai_confidence": 0
        }
        
        print("\033c", end="")
        print("="*60)
        print("❄️ SNOW DUST - Navigation Intelligence System")
        print("🤖 Self-Learning AI with TXT Reports")
        print("="*60)
        print(f"📅 Date: {datetime.now().strftime('%Y-%m-%d')}")
        print(f"🕒 Start Time: {datetime.now().strftime('%H:%M:%S')}")
        print(f"⚡ Mode: {'FAST' if fast_mode else 'NORMAL'}")
        print("="*60)
        print()
    
    def generate_sensor_data(self):
        """Generate realistic sensor data"""
        t = time.time() - self.start_time
        
        # Position with realistic movement
        base_x = 3.0 + math.sin(t * 0.02) * 0.3
        base_y = -1.2 + math.cos(t * 0.03) * 0.2
        
        position = {
            'x': base_x + random.uniform(-0.02, 0.02),
            'y': base_y + random.uniform(-0.02, 0.02),
            'z': 0.3 + math.sin(t * 0.01) * 0.1
        }
        
        # Electric field simulation
        efield_base = math.sin(t * 0.5) * 2.5
        efield = efield_base + random.uniform(-0.2, 0.2)
        
        # Confidence calculation
        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)))
        
        # Temperature
        temp_variation = math.sin(t * 0.03) * 2.0
        temperature = -26.0 + temp_variation + random.uniform(-0.2, 0.2)
        
        # Wind speed
        wind_base = 16 + math.sin(t * 0.1) * 3
        wind_speed = wind_base + random.uniform(-1, 1)
        
        data = {
            '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)
        }
        
        self.ai.prediction_log.append(data)
        return data
    
    def _simulate_wind(self, t):
        """Realistic wind simulation"""
        return math.sin(t * 0.15) * 6 + math.sin(t * 0.05) * 3
    
    def display_status(self, data, decision, evaluations_count):
        """Display system status"""
        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]} | 📊 {evaluations_count} eval", end="")
        else:
            if self.cycle_count % 3 == 0:
                print(f"{data['timestamp'][11:19]} | 📍[{data['position']['x']:5.2f},{data['position']['y']:5.2f}] | 🎯{data['confidence']:5.1f}% | 🚦{decision['color']}")
        
        sys.stdout.flush()
    
    def run(self, duration=60):
        """Run the system"""
        print("🚀 Starting navigation system... (Press Ctrl+C to stop)")
        print(f"⏱️  Duration: {duration} seconds")
        print(f"📁 Reports will be saved in: {self.report_manager.daily_dir}")
        print("-"*60)
        
        start_time = time.time()
        last_evaluation_time = time.time()
        evaluations_made = 0
        
        try:
            while time.time() - start_time < duration:
                # Generate data
                data = self.generate_sensor_data()
                self.data_buffer.append(data)
                
                # AI analysis and decision
                analysis = self.ai.analyze_environment(data)
                decision = self.ai.make_decision(data, analysis)
                
                # Make prediction
                prediction = self.ai.predict_confidence(data)
                
                # Evaluate past predictions (every 8 seconds)
                current_time = time.time()
                if current_time - last_evaluation_time >= 8 and len(self.ai.prediction_log) > 10:
                    old_prediction = list(self.ai.prediction_log)[-10]
                    evaluation = self.ai.evaluate_prediction(old_prediction, data)
                    evaluations_made += 1
                    
                    # Update statistics
                    self.session_stats["evaluations"] = evaluations_made
                    if self.session_stats["evaluations"] > 0:
                        ai_stats = self.ai.get_ai_stats()
                        self.session_stats["accuracy"] = ai_stats.get("success_rate", 0)
                        self.session_stats["ai_confidence"] = ai_stats.get("success_rate", 0) / 100
                    
                    last_evaluation_time = current_time
                
                # Display status
                self.display_status(data, decision, evaluations_made)
                
                # Update session stats
                self.session_stats["cycles"] = self.cycle_count
                self.session_stats["decisions"] = self.ai.total_decisions
                self.session_stats["duration"] = time.time() - start_time
                
                self.cycle_count += 1
                time.sleep(0.08 if self.fast_mode else 0.15)
                
        except KeyboardInterrupt:
            print("\n\n⏹️ Stopped by user")
        
        # Final processing
        self.save_reports(start_time)
        self.show_summary()
    
    def save_reports(self, start_time):
        """Save all reports"""
        # Calculate final statistics
        total_duration = time.time() - start_time
        ai_stats = self.ai.get_ai_stats()
        
        # Update session stats
        self.session_stats.update({
            "duration": total_duration,
            "cycles": self.cycle_count,
            "decisions": self.ai.total_decisions,
            "accuracy": ai_stats.get("success_rate", 0),
            "ai_confidence": ai_stats.get("success_rate", 0) / 100
        })
        
        # Add session to daily log
        self.report_manager.add_session(self.session_stats)
        
        # Get last data for report
        last_data = self.data_buffer[-1] if self.data_buffer else {}
        
        # Save session report
        session_report = self.report_manager.save_session_report(self.session_stats, last_data)
        
        # Save daily summary
        daily_summary = self.report_manager.save_daily_summary()
        
        # Print report locations
        print("\n" + "="*60)
        print("📄 REPORT SAVED SUCCESSFULLY")
        print("="*60)
        if session_report:
            print(f"Session Report: {session_report}")
        if daily_summary:
            print(f"Daily Summary: {daily_summary}")
        print("="*60)
    
    def show_summary(self):
        """Show final summary"""
        ai_stats = self.ai.get_ai_stats()
        
        print("\n" + "="*60)
        print("📊 FINAL SYSTEM SUMMARY")
        print("="*60)
        
        print(f"\n⏱️  SESSION STATISTICS:")
        print(f"  Duration: {self.session_stats['duration']:.1f} seconds")
        print(f"  Total Cycles: {self.cycle_count}")
        print(f"  Total Decisions: {self.session_stats['decisions']}")
        print(f"  Evaluations Made: {self.session_stats['evaluations']}")
        
        print(f"\n🤖 AI PERFORMANCE:")
        print(f"  Success Rate: {ai_stats.get('success_rate', 0)}%")
        print(f"  Average Error: {ai_stats.get('average_error', 0):.2f}")
        print(f"  Learning Active: {'Yes' if ai_stats.get('learning_active') else 'No'}")
        
        print(f"\n📁 DATA STORAGE:")
        print(f"  Format: TXT files only")
        print(f"  Location: {self.report_manager.daily_dir}")
        print(f"  Sessions Today: {self.report_manager.session_counter}")
        
        if self.ai.decision_history:
            last_decision = list(self.ai.decision_history)[-1]
            print(f"\n🎯 FINAL DECISION:")
            print(f"  {last_decision['color']} {last_decision['action']}")
            print(f"  Safety Score: {last_decision['safety_score']:.3f}")
        
        print("\n" + "="*60)
        print("✅ SYSTEM COMPLETED SUCCESSFULLY")
        print("="*60)

# ============================================
# 🎯 Main Function
# ============================================

def main():
    import argparse
    
    parser = argparse.ArgumentParser(description='Snow Dust Navigation System')
    parser.add_argument('--duration', '-d', type=int, default=60, 
                       help='Run duration in seconds (default: 60)')
    parser.add_argument('--fast', '-f', action='store_true',
                       help='Enable fast mode')
    
    args = parser.parse_args()
    
    system = SnowDustSystem(fast_mode=args.fast)
    system.run(duration=args.duration)

if __name__ == "__main__":
    main()
