#!/usr/bin/env python3
"""Debug frame 475 classification issue"""

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

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

def debug_frame_475(pcap_file="1 PTPGM.pcapng", src_ip="192.168.4.89"):
    """Debug why frame 475 is not in CH10-Data"""
    
    print("=== Debugging Frame 475 Classification ===")
    
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    # Track frame 475 specifically during processing
    frame_475_details = None
    
    for i, packet in enumerate(packets, 1):
        if i == 475:
            # Manually dissect to see the raw data_type_name
            try:
                dissection_results = analyzer.flow_manager._dissect_packet(packet, i)
                layers = dissection_results.get('layers', {})
                
                if 'chapter10' in layers and not layers['chapter10'].get('error'):
                    ch10_info = layers['chapter10']
                    if 'decoded_payload' in ch10_info:
                        decoded = ch10_info['decoded_payload']
                        data_type_name = decoded.get('data_type_name', 'Unknown')
                        
                        # Classify using current logic
                        classified_type = analyzer.flow_manager._classify_frame_type(packet, dissection_results)
                        
                        frame_475_details = {
                            'data_type_name': data_type_name,
                            'classified_as': classified_type
                        }
                        
                        print(f"Frame 475: data_type_name='{data_type_name}' -> classified as '{classified_type}'")
            except Exception as e:
                print(f"Error dissecting frame 475: {e}")
        
        analyzer._process_single_packet(packet, i)
    
    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"\n✅ Found flow: {test_flow.src_ip}:{test_flow.src_port} → {test_flow.dst_ip}:{test_flow.dst_port}")
    
    # Check which frame type frame 475 ended up in
    print(f"\n=== Frame 475 Final Classification ===")
    found_frame_475 = False
    
    for frame_type, ft_stats in test_flow.frame_types.items():
        if 475 in ft_stats.frame_numbers:
            frame_index = ft_stats.frame_numbers.index(475)
            timestamp = ft_stats.timestamps[frame_index]
            print(f"Frame 475 found in: {frame_type} (index {frame_index})")
            print(f"  Timestamp: {timestamp}")
            found_frame_475 = True
            
            # Show sequence around frame 475 in this frame type
            start_idx = max(0, frame_index - 3)
            end_idx = min(len(ft_stats.frame_numbers), frame_index + 4)
            
            print(f"  Sequence in {frame_type}:")
            for i in range(start_idx, end_idx):
                marker = " -> " if i == frame_index else "    "
                frame_num = ft_stats.frame_numbers[i]
                print(f"{marker}[{i}] Frame {frame_num}")
            break
    
    if not found_frame_475:
        print("❌ Frame 475 not found in any frame type!")
    
    # Check CH10-Data sequence around where frame 475 should be
    ch10_data_stats = test_flow.frame_types.get('CH10-Data')
    if ch10_data_stats:
        print(f"\n=== CH10-Data Sequence Around Frame 475 ===")
        
        # Find frames around 475 in CH10-Data
        nearby_frames = []
        for i, frame_num in enumerate(ch10_data_stats.frame_numbers):
            if abs(frame_num - 475) <= 5:
                nearby_frames.append((i, frame_num))
        
        print(f"CH10-Data frames near 475:")
        for index, frame_num in nearby_frames:
            marker = " -> " if frame_num == 476 else "    "
            print(f"{marker}[{index}] Frame {frame_num}")
    
    # Show timing analysis around frame 475-476
    print(f"\n=== Timing Analysis Around 475-476 ===")
    
    # Get all CH10 frames (any type) and sort by frame number
    all_ch10_frames = []
    for frame_type, ft_stats in test_flow.frame_types.items():
        if frame_type.startswith('CH10'):
            for i, frame_num in enumerate(ft_stats.frame_numbers):
                timestamp = ft_stats.timestamps[i]
                all_ch10_frames.append((frame_num, timestamp, frame_type))
    
    # Sort by frame number
    all_ch10_frames.sort(key=lambda x: x[0])
    
    # Show frames around 475-476
    for i, (frame_num, timestamp, frame_type) in enumerate(all_ch10_frames):
        if 473 <= frame_num <= 478:
            # Calculate delta from previous frame
            if i > 0:
                prev_timestamp = all_ch10_frames[i-1][1]
                delta_t = timestamp - prev_timestamp
                delta_str = f"Δt: {delta_t*1000:.1f}ms"
            else:
                delta_str = ""
            
            marker = " -> " if frame_num in [475, 476] else "    "
            print(f"{marker}Frame {frame_num}: {frame_type} {delta_str}")

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