#!/usr/bin/env python3
"""Debug the real-time statistics issue with frame references"""

import sys
sys.path.append('.')

from analyzer.analysis import EthernetAnalyzer
from analyzer.utils import PCAPLoader

def debug_realtime_issue(pcap_file="1 PTPGM.pcapng", src_ip="192.168.4.89"):
    """Debug why real-time mode has incorrect frame references"""
    
    print("=== Debugging Real-time Statistics Issue ===")
    
    # Initialize real-time analyzer
    analyzer = EthernetAnalyzer(enable_realtime=True, outlier_threshold_sigma=3.0)
    
    # Load packets
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    print(f"Loaded {len(packets)} packets")
    
    # Process packets one by one and monitor suspicious frame types
    suspicious_frames = []
    
    for i, packet in enumerate(packets, 1):
        analyzer._process_single_packet(packet, i)
        
        # After processing each packet, check for new outliers with suspicious gaps
        for flow_key, flow in analyzer.flows.items():
            if flow.src_ip == src_ip:
                for frame_type, ft_stats in flow.frame_types.items():
                    if hasattr(ft_stats, 'enhanced_outlier_details') and ft_stats.enhanced_outlier_details:
                        # Check the most recent outlier
                        if ft_stats.enhanced_outlier_details:
                            frame_num, prev_frame_num, delta_t = ft_stats.enhanced_outlier_details[-1]
                            frame_gap = frame_num - prev_frame_num
                            
                            # If this is a new suspicious outlier, record it
                            outlier_key = (frame_type, frame_num, prev_frame_num)
                            if frame_gap > 50 and outlier_key not in suspicious_frames:
                                suspicious_frames.append(outlier_key)
                                print(f"  Packet {i}: {frame_type} Frame {frame_num} (from {prev_frame_num}) - Gap: {frame_gap}")
                                
                                # Debug the frame sequence at this point
                                print(f"    Frame sequence length: {len(ft_stats.frame_numbers)}")
                                if len(ft_stats.frame_numbers) >= 2:
                                    print(f"    Last 5 frames: {ft_stats.frame_numbers[-5:]}")
                                    actual_prev = ft_stats.frame_numbers[-2]
                                    print(f"    Actual previous frame should be: {actual_prev}")
                                    print(f"    ❌ MISMATCH: Expected {actual_prev}, got {prev_frame_num}")
    
    print(f"\nTotal suspicious outliers found: {len(suspicious_frames)}")
    
    # Let's also check one specific frame type in detail
    flow = None
    for flow_key, f in analyzer.flows.items():
        if f.src_ip == src_ip:
            flow = f
            break
    
    if flow:
        print(f"\n=== Detailed Analysis of CH10-Extended ===")
        extended_stats = flow.frame_types.get('CH10-Extended')
        if extended_stats:
            print(f"Total frames: {len(extended_stats.frame_numbers)}")
            print(f"Frame numbers: {extended_stats.frame_numbers}")
            print(f"Outliers: {len(extended_stats.outlier_frames)}")
            
            if hasattr(extended_stats, 'enhanced_outlier_details'):
                for frame_num, prev_frame_num, delta_t in extended_stats.enhanced_outlier_details:
                    # Find actual index
                    if frame_num in extended_stats.frame_numbers:
                        actual_index = extended_stats.frame_numbers.index(frame_num)
                        if actual_index > 0:
                            actual_prev = extended_stats.frame_numbers[actual_index - 1]
                            status = "✅" if prev_frame_num == actual_prev else f"❌ (should be {actual_prev})"
                            print(f"  Frame {frame_num} from {prev_frame_num}: {status}")

if __name__ == "__main__":
    if len(sys.argv) > 1:
        debug_realtime_issue(sys.argv[1])
    else:
        debug_realtime_issue()