#!/usr/bin/env python3
"""Simulate what the UI displays"""

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

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

def simulate_ui_display(pcap_file, src_ip="192.168.4.89"):
    """Simulate what the UI would display"""
    
    # 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("=== UI DISPLAY SIMULATION ===\n")
    
    # Main flow row
    print(f"MAIN FLOW ROW:")
    print(f"  {target_flow.src_ip}:{target_flow.src_port} -> {target_flow.dst_ip}:{target_flow.dst_port}")
    print(f"  Protocol: {target_flow.transport_protocol}")
    print(f"  Packets: {target_flow.frame_count}")
    print(f"  Outliers Column: {len(target_flow.outlier_frames)}")  # This is what shows in main row
    print(f"  ^-- This should show in the 'Out' column for the main flow")
    
    # For enhanced flows, show subrows
    if target_flow.enhanced_analysis.decoder_type != "Standard":
        print(f"\nSUBROWS (Frame Types):")
        
        # Sort by count like UI does
        sorted_types = sorted(
            target_flow.frame_types.items(),
            key=lambda x: x[1].count,
            reverse=True
        )
        
        for frame_type, stats in sorted_types:
            outlier_count = len(stats.outlier_frames)
            print(f"\n  Frame Type: {frame_type}")
            print(f"    Count: {stats.count}")
            print(f"    Outliers Column: {outlier_count}")  # This is what shows in subrow
            if outlier_count > 0:
                print(f"    ^-- This shows in 'Out' column for this subrow")
    
    # Check if any number is 19
    print("\n=== CHECKING FOR 19 ===")
    
    # Main flow
    if len(target_flow.outlier_frames) == 19:
        print("✅ Main flow row shows 19 outliers!")
    
    # Frame types
    for frame_type, stats in target_flow.frame_types.items():
        if len(stats.outlier_frames) == 19:
            print(f"✅ Frame type '{frame_type}' shows 19 outliers!")
    
    # Could it be counting unique packet numbers?
    print("\n=== OTHER POSSIBILITIES ===")
    
    # Count total unique packets that are outliers in ANY frame type
    all_outlier_packets = set()
    for frame_type, stats in target_flow.frame_types.items():
        all_outlier_packets.update(stats.outlier_frames)
    
    print(f"Total unique packets that are outliers in ANY frame type: {len(all_outlier_packets)}")
    if len(all_outlier_packets) == 19:
        print("⚠️ Possible bug: UI might be counting unique outlier packets across all frame types!")

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