#!/usr/bin/env python3
"""
最终测试版本 - 使用修复后的EZAI库
"""

import os
import sys
import time
import cv2

# 设置显示环境
os.environ["DISPLAY"] = ":0"

def test_fixed_ezai():
    """测试修复后的EZAI版本"""
    print("=== 测试修复后的EZAI版本 ===")
    
    try:
        # 导入修复后的ezai
        sys.path.insert(0, '..')
        import ezai.go2 as go2
        
        print("1. 初始化Go2机器人...")
        robot = go2.Go2()
        print(f"   检测到接口: {robot.interface}")
        
        print("2. 初始化连接...")
        robot.init()
        print("   ✅ Go2连接成功")
        
        print("3. 创建视频读取器...")
        # 强制使用管道方法
        read_frame, cleanup = robot.get_video_reader(method='pipe')
        
        if read_frame is None:
            print("   ❌ 无法创建视频读取器")
            return False
        
        print("   ✅ 视频读取器创建成功")
        
        print("4. 开始读取视频流...")
        print("   按q键退出，按s键保存截图")
        
        frame_count = 0
        success_count = 0
        save_count = 0
        
        while True:
            frame = read_frame()
            
            if frame is not None:
                # 显示图像
                cv2.imshow('Go2视频流 - EZAI修复版', frame)
                frame_count += 1
                success_count += 1
                
                # 每30帧显示统计
                if frame_count % 30 == 0:
                    print(f"   ✅ 成功显示 {success_count} 帧 (尺寸: {frame.shape})")
                
                # 检查按键
                key = cv2.waitKey(1) & 0xFF
                if key == ord('q'):
                    break
                elif key == ord('s'):
                    # 保存截图
                    filename = f"go2_frame_{success_count:06d}.jpg"
                    cv2.imwrite(filename, frame)
                    print(f"   💾 保存截图: {filename}")
                    save_count += 1
            else:
                frame_count += 1
                # 每30次失败显示统计
                if frame_count % 30 == 0:
                    print(f"   ⏳ 等待视频数据... (成功率: {success_count}/{frame_count} = {success_count/frame_count*100:.1f}%)")
                
                # 短暂等待
                time.sleep(0.01)
                
    except Exception as e:
        print(f"❌ 测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # 清理资源
        if cleanup:
            cleanup()
        cv2.destroyAllWindows()
        
        print(f"\n=== 测试完成 ===")
        print(f"总尝试帧数: {frame_count}")
        print(f"成功显示帧数: {success_count}")
        print(f"保存截图数: {save_count}")
        if frame_count > 0:
            print(f"成功率: {success_count/frame_count*100:.1f}%")
        
        return success_count > 0

def compare_with_pipstream():
    """与pipstream.py对比"""
    print("\n=== 与pipstream.py对比测试 ===")
    print("如果pipstream.py工作但EZAI不工作，请检查:")
    print("1. 网络接口是否一致")
    print("2. GStreamer命令是否相同")
    print("3. 管道读取逻辑是否一致")
    
    # 显示关键差异
    print("\n关键参数对比:")
    print("- pipstream.py接口: enx00e0986113a6")
    print("- EZAI检测接口: ", end="")
    
    try:
        sys.path.insert(0, '..')
        import ezai.go2 as go2
        robot = go2.Go2()
        print(robot.interface)
    except:
        print("无法检测")

if __name__ == "__main__":
    print("Go2视频流最终测试 - EZAI v1.2.2")
    print("=" * 50)
    
    success = test_fixed_ezai()
    
    if not success:
        print("\n❌ 测试失败，运行对比分析...")
        compare_with_pipstream()
        print("\n建议:")
        print("1. 先运行 pipstream.py 确认硬件工作")
        print("2. 运行 go2_debug_interface.py 检查接口")
        print("3. 检查网络连接和Go2机器人状态")
    else:
        print("\n✅ 测试成功！EZAI封装工作正常")