#!/usr/bin/env python3
"""Debug frame type outliers"""

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

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

def debug_frame_outliers(pcap_file, src_ip="192.168.4.89"):
    """Debug outliers at frame type level"""
    
    # Create analyzer
    analyzer = EthernetAnalyzer(outlier_threshold_sigma=3.0)
    
    # Load PCAP
    loader = PCAPLoader(pcap_file)
    packets = loader.load_all()
    
    # Process packets
    for i, packet in enumerate(packets, 1):
        analyzer._process_single_packet(packet, i)
    
    # Calculate statistics
    analyzer.calculate_statistics()
    
    # Find the specific flow
    target_flow = None
    for flow_key, flow in analyzer.flows.items():
        if flow.src_ip == src_ip:
            target_flow = flow
            break
    
    if not target_flow:
        print(f"Flow from {src_ip} not found!")
        return
    
    print(f"Flow: {target_flow.src_ip}:{target_flow.src_port} -> {target_flow.dst_ip}:{target_flow.dst_port}")
    print(f"Total packets: {target_flow.frame_count}")
    print(f"Flow-level outliers: {len(target_flow.outlier_frames)} frames")
    print(f"Flow outlier frames: {sorted(target_flow.outlier_frames)}")
    
    print("\n=== Frame Type Analysis ===")
    total_frame_type_outliers = 0
    all_frame_type_outliers = set()
    
    for frame_type, stats in sorted(target_flow.frame_types.items(), key=lambda x: x[1].count, reverse=True):
        if stats.outlier_frames:
            total_frame_type_outliers += len(stats.outlier_frames)
            all_frame_type_outliers.update(stats.outlier_frames)
            
        print(f"\nFrame Type: {frame_type}")
        print(f"  Count: {stats.count}")
        print(f"  Outliers: {len(stats.outlier_frames)}")
        if stats.outlier_frames:
            print(f"  Outlier frames: {sorted(stats.outlier_frames)[:10]}")
            if len(stats.outlier_frames) > 10:
                print(f"  ... and {len(stats.outlier_frames) - 10} more")
        print(f"  Avg ΔT: {stats.avg_inter_arrival * 1000:.3f} ms")
        print(f"  Std σ: {stats.std_inter_arrival * 1000:.3f} ms")
    
    print(f"\n=== Summary ===")
    print(f"Flow-level outliers: {len(target_flow.outlier_frames)}")
    print(f"Sum of frame type outliers: {total_frame_type_outliers}")
    print(f"Unique frames with outliers across all types: {len(all_frame_type_outliers)}")
    
    # Check if UI might be showing sum of frame type outliers
    if total_frame_type_outliers == 19:
        print("\n⚠️ Found it! The UI might be showing the SUM of outliers across frame types!")
    elif len(all_frame_type_outliers) == 19:
        print("\n⚠️ Found it! The UI might be showing unique outlier frames across all frame types!")

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