#!/usr/bin/env python3
"""
调试版本 - 检查图像数据和显示问题
"""

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

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

def debug_video_test():
    """调试视频显示问题"""
    print("=== 调试版本测试 ===")
    
    # 1. 获取接口
    sys.path.insert(0, '..')
    import ezai.go2 as go2
    
    robot = go2.Go2()
    robot.init()
    interface = robot.interface
    print(f"检测到接口: {interface}")
    
    # 2. 创建视频流
    pipe_path = "/tmp/debug_test_pipe"
    width, height = 1280, 720
    
    # 清理旧管道
    if os.path.exists(pipe_path):
        os.remove(pipe_path)
    
    # 创建管道
    os.mkfifo(pipe_path)
    print("命名管道已创建")
    
    # 启动GStreamer
    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 True:
                frame_data = pipe.read(frame_size)
                
                if len(frame_data) == frame_size:
                    # 转换为图像
                    frame = np.frombuffer(frame_data, dtype=np.uint8).reshape((height, width, 3))
                    
                    # 调试信息
                    if frame_count == 0:
                        print(f"第一帧信息:")
                        print(f"  图像尺寸: {frame.shape}")
                        print(f"  数据类型: {frame.dtype}")
                        print(f"  像素值范围: {frame.min()} - {frame.max()}")
                        print(f"  前10个像素值: {frame.flat[:10]}")
                        
                        # 保存第一帧到文件检查
                        cv2.imwrite('/tmp/debug_first_frame.jpg', frame)
                        print("  第一帧已保存到: /tmp/debug_first_frame.jpg")
                    
                    # 显示图像
                    cv2.imshow('Go2视频流 (调试版本)', frame)
                    frame_count += 1
                    
                    if frame_count % 30 == 0:
                        print(f"✅ 处理第 {frame_count} 帧")
                    
                    # 等待按键，确保窗口刷新
                    key = cv2.waitKey(1) & 0xFF
                    if key == ord('q'):
                        break
                    elif key == ord('s'):
                        # 手动保存当前帧
                        cv2.imwrite(f'/tmp/debug_frame_{frame_count}.jpg', frame)
                        print(f"保存第 {frame_count} 帧到: /tmp/debug_frame_{frame_count}.jpg")
                else:
                    # 数据不完整时等待
                    cv2.waitKey(1)
                    
    except Exception as e:
        print(f"错误: {e}")
        import traceback
        traceback.print_exc()
    finally:
        # 清理
        os.system("pkill -f gst-launch")
        if os.path.exists(pipe_path):
            os.remove(pipe_path)
        cv2.destroyAllWindows()
        print("程序结束")

if __name__ == "__main__":
    debug_video_test()