#!/usr/bin/env python3
"""
Safe version of StreamLens with segfault protections
"""

import sys
import os
import signal
import traceback

# Add the analyzer package to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

def signal_handler(signum, frame):
    """Handle segmentation faults gracefully"""
    print(f"\n💥 Received signal {signum}")
    print("Segmentation fault detected - cleaning up...")
    sys.exit(1)

def safe_import():
    """Safely import analyzer components"""
    try:
        from analyzer.main import main
        return main
    except Exception as e:
        print(f"Import error: {e}")
        traceback.print_exc()
        return None

def main():
    """Safe main function with error handling"""
    # Set up signal handlers
    signal.signal(signal.SIGSEGV, signal_handler)
    signal.signal(signal.SIGABRT, signal_handler)
    
    print("🛡️  Starting StreamLens in safe mode...")
    
    try:
        # Import main function safely
        main_func = safe_import()
        if main_func is None:
            print("Failed to import analyzer")
            sys.exit(1)
            
        # Check command line arguments
        if len(sys.argv) > 1 and '--pcap' in sys.argv:
            pcap_index = sys.argv.index('--pcap')
            if pcap_index + 1 < len(sys.argv):
                pcap_file = sys.argv[pcap_index + 1]
                print(f"📁 Loading PCAP: {pcap_file}")
                
                # Check file size and warn if large
                if os.path.exists(pcap_file):
                    size_mb = os.path.getsize(pcap_file) / (1024 * 1024)
                    print(f"📊 File size: {size_mb:.1f} MB")
                    
                    if size_mb > 100:
                        print("⚠️  Large file detected - this may take a while...")
        
        # Disable signal visualization for safety
        print("🔒 Disabling signal visualization for safety...")
        os.environ['STREAMLENS_DISABLE_VISUALIZATION'] = '1'
        
        # Run the main analyzer
        print("🚀 Starting analysis...")
        main_func()
        
    except KeyboardInterrupt:
        print("\n⏹️  Analysis interrupted by user")
        sys.exit(0)
    except Exception as e:
        print(f"\n💥 Unexpected error: {e}")
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()