#!/usr/bin/env python3
"""Debug CH10 frame type classification"""

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

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

def debug_ch10_frame_types(pcap_file="1 PTPGM.pcapng", src_ip="192.168.4.89"):
    """Debug CH10 frame type classification"""
    
    print("=== Debugging CH10 Frame Type Classification ===")
    
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    # Track frame classification details
    frame_details = {}
    
    for i, packet in enumerate(packets, 1):
        analyzer._process_single_packet(packet, i)
        
        # Capture details for specific problematic frames
        if i in [485, 486, 955, 956, 957]:
            # Get the flow
            for flow_key, flow in analyzer.flows.items():
                if flow.src_ip == src_ip:
                    # Find which frame type this packet was classified as
                    for frame_type, ft_stats in flow.frame_types.items():
                        if i in ft_stats.frame_numbers:
                            frame_details[i] = {
                                'frame_type': frame_type,
                                'timestamp': ft_stats.timestamps[ft_stats.frame_numbers.index(i)]
                            }
                            break
                    break
    
    analyzer.calculate_statistics()
    
    # Find test flow
    test_flow = None
    for flow_key, flow in analyzer.flows.items():
        if flow.src_ip == src_ip:
            test_flow = flow
            break
    
    if not test_flow:
        print(f"❌ No flow found from {src_ip}")
        return
    
    print(f"✅ Found flow: {test_flow.src_ip}:{test_flow.src_port} → {test_flow.dst_ip}:{test_flow.dst_port}")
    
    # Show classification of problematic frames
    print(f"\n=== Frame Classification Details ===")
    problem_frames = [485, 486, 955, 956, 957]
    
    for frame_num in problem_frames:
        if frame_num in frame_details:
            detail = frame_details[frame_num]
            print(f"Frame {frame_num}: {detail['frame_type']} (ts: {detail['timestamp']:.6f})")
        else:
            print(f"Frame {frame_num}: Not found in flow {src_ip}")
    
    # Show timing between consecutive frames regardless of classification
    print(f"\n=== Raw Timing Analysis (ignoring frame type) ===")
    all_frames = []
    for frame_type, ft_stats in test_flow.frame_types.items():
        if frame_type.startswith('CH10'):  # All CH10 variants
            for i, frame_num in enumerate(ft_stats.frame_numbers):
                all_frames.append((frame_num, ft_stats.timestamps[i], frame_type))
    
    # Sort by frame number
    all_frames.sort(key=lambda x: x[0])
    
    # Show timing around problematic frames
    for target_frame in [486, 957]:
        print(f"\n--- Timing around frame {target_frame} ---")
        
        # Find target frame in sorted list
        target_idx = None
        for i, (frame_num, timestamp, frame_type) in enumerate(all_frames):
            if frame_num == target_frame:
                target_idx = i
                break
        
        if target_idx is not None:
            # Show 3 frames before and after
            start_idx = max(0, target_idx - 3)
            end_idx = min(len(all_frames), target_idx + 4)
            
            for i in range(start_idx, end_idx):
                frame_num, timestamp, frame_type = all_frames[i]
                marker = " -> " if i == target_idx else "    "
                
                # Calculate delta from previous CH10 frame (any type)
                if i > start_idx:
                    prev_timestamp = all_frames[i-1][1]
                    delta_t = timestamp - prev_timestamp
                    delta_str = f"Δt: {delta_t*1000:.1f}ms"
                else:
                    delta_str = ""
                
                print(f"{marker}Frame {frame_num}: {frame_type} {delta_str}")
    
    # Show frame type statistics
    print(f"\n=== CH10 Frame Type Statistics ===")
    ch10_types = {k: v for k, v in test_flow.frame_types.items() if k.startswith('CH10')}
    
    for frame_type, ft_stats in sorted(ch10_types.items(), key=lambda x: len(x[1].frame_numbers), reverse=True):
        count = len(ft_stats.frame_numbers)
        avg_delta = ft_stats.avg_inter_arrival * 1000 if ft_stats.avg_inter_arrival > 0 else 0
        outliers = len(ft_stats.outlier_frames)
        print(f"{frame_type}: {count} frames, avg Δt: {avg_delta:.1f}ms, outliers: {outliers}")
        
        # Show frame number ranges
        if ft_stats.frame_numbers:
            min_frame = min(ft_stats.frame_numbers)
            max_frame = max(ft_stats.frame_numbers)
            print(f"  Frame range: {min_frame} - {max_frame}")

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