#!/usr/bin/env python3
"""
Test the tabbed interface integration
"""

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

from analyzer.analysis import EthernetAnalyzer
from analyzer.analysis.background_analyzer import BackgroundAnalyzer
import time

def test_tabbed_interface():
    """Test that the tabbed interface can detect frame types"""
    print("=== Testing Tabbed Interface Frame Type Detection ===")
    
    # Create analyzer
    analyzer = EthernetAnalyzer(enable_realtime=False, outlier_threshold_sigma=3.0)
    
    # Process the PCAP file
    bg_analyzer = BackgroundAnalyzer(analyzer, num_threads=1)
    bg_analyzer.start_parsing("1 PTPGM.pcapng")
    
    # Wait for completion
    start_time = time.time()
    while bg_analyzer.is_parsing:
        time.sleep(0.1)
        if time.time() - start_time > 30:
            break
    
    bg_analyzer.cleanup()
    
    # Analyze detected frame types
    print(f"\\n📊 Flow Analysis Results:")
    print(f"   Total flows: {len(analyzer.flows)}")
    
    all_frame_types = set()
    flow_frame_type_summary = {}
    
    for i, (flow_key, flow) in enumerate(analyzer.flows.items()):
        print(f"\\n🔍 Flow {i+1}: {flow.src_ip}:{flow.src_port} → {flow.dst_ip}:{flow.dst_port}")
        print(f"   Transport: {flow.transport_protocol}")
        print(f"   Total packets: {flow.frame_count}")
        
        if flow.frame_types:
            print(f"   Frame types ({len(flow.frame_types)}):")
            for frame_type, ft_stats in sorted(flow.frame_types.items(), key=lambda x: x[1].count, reverse=True):
                all_frame_types.add(frame_type)
                
                # Track frame type usage
                if frame_type not in flow_frame_type_summary:
                    flow_frame_type_summary[frame_type] = {"flows": 0, "total_packets": 0}
                flow_frame_type_summary[frame_type]["flows"] += 1
                flow_frame_type_summary[frame_type]["total_packets"] += ft_stats.count
                
                # Show frame type details
                avg_delta = f"{ft_stats.avg_inter_arrival * 1000:.1f}ms" if ft_stats.avg_inter_arrival > 0 else "N/A"
                outliers = len(ft_stats.outlier_frames)
                print(f"     - {frame_type}: {ft_stats.count} packets, avg Δt: {avg_delta}, outliers: {outliers}")
        else:
            print(f"   No frame types detected")
    
    # Summary for tabbed interface
    print(f"\\n📋 Tabbed Interface Summary:")
    print(f"   Detected frame types: {len(all_frame_types)}")
    print(f"   Tabs needed: Overview + {len(all_frame_types)} frame-specific tabs")
    
    print(f"\\n🏷️  Frame Type Distribution:")
    for frame_type, stats in sorted(flow_frame_type_summary.items(), key=lambda x: x[1]["total_packets"], reverse=True):
        print(f"   {frame_type}: {stats['flows']} flows, {stats['total_packets']:,} packets")
    
    # Recommend tab structure
    print(f"\\n📑 Recommended Tab Structure:")
    print(f"   1. Overview Tab: All flows summary")
    
    tab_num = 2
    for frame_type in sorted(all_frame_types):
        stats = flow_frame_type_summary[frame_type]
        print(f"   {tab_num}. {frame_type} Tab: {stats['flows']} flows, {stats['total_packets']:,} packets")
        tab_num += 1
    
    print(f"\\n✅ Tabbed interface test completed!")
    print(f"📊 Expected behavior:")
    print(f"   - Overview tab shows all flows with mixed frame types")
    print(f"   - Each frame-specific tab shows flows filtered to that frame type")
    print(f"   - Frame-specific tabs show detailed statistics for that frame type")
    
    return len(all_frame_types) > 0

if __name__ == "__main__":
    success = test_tabbed_interface()
    if success:
        print("\\n🎉 Test passed - Frame types detected!")
    else:
        print("\\n❌ Test failed - No frame types detected")
        sys.exit(1)