#!/usr/bin/env python3
"""Debug frame reference tracking for subflows"""

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

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

def debug_frame_references(pcap_file="1 PTPGM.pcapng", src_ip="192.168.4.89"):
    """Debug frame reference tracking in subflows"""
    
    print("=== Debugging Frame References in Subflows ===")
    
    # Initialize analyzer
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    # Load and process packets
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    print(f"Loaded {len(packets)} packets")
    
    # Process packets
    for i, packet in enumerate(packets, 1):
        analyzer._process_single_packet(packet, i)
    
    # Calculate statistics
    analyzer.calculate_statistics()
    
    # Find the 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}")
    
    # Focus on CH10-Data subflow
    ch10_data_stats = test_flow.frame_types.get('CH10-Data')
    if not ch10_data_stats:
        print("❌ No CH10-Data frame type found")
        return
    
    print(f"\n=== CH10-Data Subflow Analysis ===")
    print(f"Total CH10-Data frames: {ch10_data_stats.count}")
    print(f"Frame numbers tracked: {len(ch10_data_stats.frame_numbers)}")
    print(f"Inter-arrival times: {len(ch10_data_stats.inter_arrival_times)}")
    
    # Show first 10 and last 10 frame numbers to verify sequence
    print(f"\nFirst 10 CH10-Data frame numbers: {ch10_data_stats.frame_numbers[:10]}")
    print(f"Last 10 CH10-Data frame numbers: {ch10_data_stats.frame_numbers[-10:]}")
    
    # Check for frame 1001 specifically
    target_frame = 1001
    if target_frame in ch10_data_stats.frame_numbers:
        frame_index = ch10_data_stats.frame_numbers.index(target_frame)
        print(f"\n🎯 Frame {target_frame} analysis:")
        print(f"  Index in CH10-Data sequence: {frame_index}")
        print(f"  Total CH10-Data frames before this: {frame_index}")
        
        if frame_index > 0:
            prev_frame_in_subflow = ch10_data_stats.frame_numbers[frame_index - 1]
            print(f"  Previous CH10-Data frame: {prev_frame_in_subflow}")
        else:
            print(f"  This is the first CH10-Data frame")
        
        # Check if this frame is in outliers
        if hasattr(ch10_data_stats, 'enhanced_outlier_details'):
            for frame_num, prev_frame_num, delta_t in ch10_data_stats.enhanced_outlier_details:
                if frame_num == target_frame:
                    print(f"  ⚠️  OUTLIER: Frame {frame_num} (from {prev_frame_num}): {delta_t * 1000:.3f} ms")
                    
                    # Verify this matches our expectation
                    if frame_index > 0:
                        expected_prev = ch10_data_stats.frame_numbers[frame_index - 1]
                        if prev_frame_num == expected_prev:
                            print(f"  ✅ Frame reference is CORRECT: {prev_frame_num}")
                        else:
                            print(f"  ❌ Frame reference is WRONG: got {prev_frame_num}, expected {expected_prev}")
                    break
            else:
                print(f"  Frame {target_frame} is not an outlier")
    else:
        print(f"\n❌ Frame {target_frame} not found in CH10-Data subflow")
    
    # Show some outlier details for verification
    if hasattr(ch10_data_stats, 'enhanced_outlier_details') and ch10_data_stats.enhanced_outlier_details:
        print(f"\n=== Enhanced Outlier Details Verification ===")
        for frame_num, prev_frame_num, delta_t in ch10_data_stats.enhanced_outlier_details[:5]:
            # Find the index of this frame in the subflow
            if frame_num in ch10_data_stats.frame_numbers:
                frame_index = ch10_data_stats.frame_numbers.index(frame_num)
                if frame_index > 0:
                    expected_prev = ch10_data_stats.frame_numbers[frame_index - 1]
                    status = "✅ CORRECT" if prev_frame_num == expected_prev else f"❌ WRONG (expected {expected_prev})"
                    print(f"Frame {frame_num} (from {prev_frame_num}): {status}")
                else:
                    print(f"Frame {frame_num} (from {prev_frame_num}): ⚠️  First frame in subflow")
    
    # Show the calculation logic for inter-arrival times
    print(f"\n=== Inter-arrival Time Calculation Verification ===")
    print("First 5 inter-arrival calculations:")
    for i in range(min(5, len(ch10_data_stats.inter_arrival_times))):
        if i + 1 < len(ch10_data_stats.timestamps):
            delta_t = ch10_data_stats.inter_arrival_times[i]
            curr_frame = ch10_data_stats.frame_numbers[i + 1]
            prev_frame = ch10_data_stats.frame_numbers[i]
            curr_ts = ch10_data_stats.timestamps[i + 1]
            prev_ts = ch10_data_stats.timestamps[i]
            calculated_delta = curr_ts - prev_ts
            
            print(f"  [{i}] Frame {curr_frame} - Frame {prev_frame}: {delta_t:.6f}s (calc: {calculated_delta:.6f}s)")

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