#!/usr/bin/env python3
"""Debug actual data_type_name values for problematic frames"""

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

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

def debug_data_type_names(pcap_file="1 PTPGM.pcapng", src_ip="192.168.4.89"):
    """Debug actual data_type_name values"""
    
    print("=== Debugging data_type_name Values ===")
    
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    # Collect data_type_name for each frame type seen
    data_type_samples = {}
    
    # Process first 100 packets to get samples
    for i, packet in enumerate(packets[:100], 1):
        # 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)
                    
                    if classified_type not in data_type_samples:
                        data_type_samples[classified_type] = set()
                    
                    data_type_samples[classified_type].add(data_type_name)
                    
                    # Show specific problematic frames
                    if i in [1, 2, 6, 8, 9, 10, 11, 485, 955]:
                        print(f"Frame {i}: data_type_name='{data_type_name}' -> classified as '{classified_type}'")
        except Exception as e:
            continue
    
    # Show classification mapping
    print(f"\n=== Classification Mapping ===")
    for classified_type, data_type_names in sorted(data_type_samples.items()):
        print(f"{classified_type}:")
        for name in sorted(data_type_names):
            print(f"  - '{name}'")
    
    # Now run full analysis to see timing patterns
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    for i, packet in enumerate(packets, 1):
        analyzer._process_single_packet(packet, i)
    
    analyzer.calculate_statistics()
    
    # Find test flow and show timing patterns
    test_flow = None
    for flow_key, flow in analyzer.flows.items():
        if flow.src_ip == src_ip:
            test_flow = flow
            break
    
    if test_flow:
        print(f"\n=== Timing Patterns ===")
        for frame_type, ft_stats in sorted(test_flow.frame_types.items()):
            if frame_type.startswith('CH10'):
                count = len(ft_stats.frame_numbers)
                avg_ms = ft_stats.avg_inter_arrival * 1000 if ft_stats.avg_inter_arrival > 0 else 0
                print(f"{frame_type}: {count} frames, avg Δt: {avg_ms:.1f}ms")
                
                # Show first few frame numbers to understand the pattern
                if ft_stats.frame_numbers:
                    first_frames = ft_stats.frame_numbers[:5]
                    print(f"  First frames: {first_frames}")

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