#!/usr/bin/env python3
"""
对比测试 - pipstream.py vs 动态接口
"""

import os
import sys
import time
import cv2
import numpy as np

os.environ["DISPLAY"] = ":0"

def test_original_pipstream():
    """测试原始pipstream.py（固定接口）"""
    print("=== 测试原始pipstream.py ===")
    
    pipe_path = "/tmp/original_pipe"
    width, height = 1280, 720
    
    # 清理旧管道
    if os.path.exists(pipe_path):
        os.remove(pipe_path)
    
    # 创建管道
    os.mkfifo(pipe_path)
    print("命名管道已创建")
    
    # 使用固定接口（原始pipstream.py的方式）
    gst_cmd = (
        "exec gst-launch-1.0 udpsrc address=230.1.1.1 port=1720 multicast-iface=enx00e0986113a6 "
        "! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse "
        "! avdec_h264 ! videoconvert ! video/x-raw,format=BGR,width=1280,height=720 "
        "! filesink location=" + pipe_path + " > /dev/null 2>&1 &"
    )
    
    print("启动GStreamer（固定接口）...")
    os.system(gst_cmd)
    time.sleep(3)
    
    try:
        print("开始读取视频...")
        frame_size = width * height * 3
        
        with open(pipe_path, 'rb') as pipe:
            frame_count = 0
            while frame_count < 90:  # 只读90帧做对比
                frame_data = pipe.read(frame_size)
                
                if len(frame_data) == frame_size:
                    frame = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width, 3))
                    cv2.imshow('原始pipstream.py', frame)
                    frame_count += 1
                    
                    if frame_count % 30 == 0:
                        print(f"✅ 原始版本显示第 {frame_count} 帧")
                    
                    cv2.waitKey(1)
                else:
                    cv2.waitKey(1)
                
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                    
    except Exception as e:
        print(f"原始版本错误: {e}")
    finally:
        os.system("pkill -f gst-launch")
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
        cv2.destroyAllWindows()
        print("原始版本测试结束")

def test_dynamic_interface():
    """测试动态接口版本"""
    print("\n=== 测试动态接口版本 ===")
    
    # 获取动态接口
    sys.path.insert(0, '..')
    import ezai.go2 as go2
    
    robot = go2.Go2()
    robot.init()
    interface = robot.interface
    print(f"检测到接口: {interface}")
    
    pipe_path = "/tmp/dynamic_pipe"
    width, height = 1280, 720
    
    # 清理旧管道
    if os.path.exists(pipe_path):
        os.remove(pipe_path)
    
    # 创建管道
    os.mkfifo(pipe_path)
    print("命名管道已创建")
    
    # 使用动态接口
    gst_cmd = (
        "exec gst-launch-1.0 udpsrc address=230.1.1.1 port=1720 multicast-iface=" + interface + " "
        "! application/x-rtp, media=video, encoding-name=H264 ! rtph264depay ! h264parse "
        "! avdec_h264 ! videoconvert ! video/x-raw,format=BGR,width=1280,height=720 "
        "! filesink location=" + pipe_path + " > /dev/null 2>&1 &"
    )
    
    print("启动GStreamer（动态接口）...")
    os.system(gst_cmd)
    time.sleep(3)
    
    try:
        print("开始读取视频...")
        frame_size = width * height * 3
        
        with open(pipe_path, 'rb') as pipe:
            frame_count = 0
            while frame_count < 90:  # 只读90帧做对比
                frame_data = pipe.read(frame_size)
                
                if len(frame_data) == frame_size:
                    frame = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width, 3))
                    cv2.imshow('动态接口版本', frame)
                    frame_count += 1
                    
                    if frame_count % 30 == 0:
                        print(f"✅ 动态版本显示第 {frame_count} 帧")
                    
                    cv2.waitKey(1)
                else:
                    cv2.waitKey(1)
                
                if cv2.waitKey(1) & 0xFF == ord('q'):
                    break
                    
    except Exception as e:
        print(f"动态版本错误: {e}")
    finally:
        os.system("pkill -f gst-launch")
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
        cv2.destroyAllWindows()
        print("动态版本测试结束")

if __name__ == "__main__":
    print("选择测试模式:")
    print("1. 原始pipstream.py（固定接口）")
    print("2. 动态接口版本")
    print("3. 两个版本都测试")
    
    try:
        choice = input("请选择 (1/2/3): ").strip()
        
        if choice == "1":
            test_original_pipstream()
        elif choice == "2":
            test_dynamic_interface()
        elif choice == "3":
            test_original_pipstream()
            time.sleep(2)
            test_dynamic_interface()
        else:
            print("默认运行两个版本...")
            test_original_pipstream()
            time.sleep(2)
            test_dynamic_interface()
            
    except KeyboardInterrupt:
        print("\n测试被用户中断")
    except Exception as e:
        print(f"测试异常: {e}")