#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
EZAI基础使用示例
"""

import time
import cv2

def example_camera():
    """摄像头使用示例"""
    print("=== 摄像头示例 ===")
    
    from ezai import Camera, OpenCVUI
    
    # 创建摄像头和UI对象
    camera = Camera()
    ui = OpenCVUI()
    
    print("按 'q' 键退出，按 's' 键保存图片")
    
    try:
        while True:
            # 捕获图像
            image = camera.capture()
            if image is None:
                print("无法捕获图像")
                break
            
            # 显示图像
            ui.show_image("EZAI Camera", image)
            
            # 等待按键
            key = ui.waitKey(1) & 0xFF
            if key == ord('q'):
                break
            elif key == ord('s'):
                # 保存图片
                filename = f"capture_{int(time.time())}.jpg"
                cv2.imwrite(filename, image)
                print(f"图片已保存: {filename}")
                
    except KeyboardInterrupt:
        print("\n用户中断")
    finally:
        ui.destroyAllWindows()

def example_go2():
    """Go2机器狗控制示例"""
    print("=== Go2机器狗示例 ===")
    
    try:
        from ezai import Go2
        
        # 创建Go2控制器
        dog = Go2()
        
        # 连接机器狗
        if dog.connect():
            print("✅ Go2连接成功")
            
            try:
                # 前进2秒
                print("前进中...")
                dog.move(0.5, 0, 0)  # vx=0.5, vy=0, vyaw=0
                time.sleep(2)
                
                # 后退2秒
                print("后退中...")
                dog.move(-0.5, 0, 0)
                time.sleep(2)
                
                # 左转2秒
                print("左转中...")
                dog.move(0, 0, 1.0)  # vx=0, vy=0, vyaw=1.0
                time.sleep(2)
                
                # 停止
                print("停止")
                dog.move(0, 0, 0)
                
            finally:
                # 断开连接
                dog.disconnect()
                print("✅ 已断开连接")
        else:
            print("❌ Go2连接失败")
            
    except ImportError:
        print("❌ Go2模块不可用，请安装 unitree-sdk2py")
    except Exception as e:
        print(f"❌ Go2控制出错: {e}")

def example_onnx():
    """ONNX推理示例"""
    print("=== ONNX推理示例 ===")
    
    try:
        from ezai import ONNXWorkflow
        
        # 创建测试图像
        test_image = cv2.imread("test.jpg")
        if test_image is None:
            # 创建一个随机测试图像
            test_image = cv2.rectangle(
                cv2.zeros((224, 224, 3), dtype=cv2.uint8),
                (50, 50), (174, 174), (255, 255, 255), -1
            )
            print("使用随机测试图像")
        else:
            print("使用 test.jpg")
        
        # 创建ONNX工作流（需要模型文件）
        try:
            workflow = ONNXWorkflow("model.onnx")
            result = workflow.run(test_image)
            print(f"✅ ONNX推理结果: {result}")
        except FileNotFoundError:
            print("⚠️ 需要提供 model.onnx 文件")
        except Exception as e:
            print(f"⚠️ ONNX推理失败: {e}")
            
    except ImportError:
        print("❌ ONNX模块不可用，请安装 onnx 依赖")

def main():
    """主函数"""
    print("EZAI基础使用示例")
    print("=" * 40)
    
    # 显示可用模块
    from ezai import get_available_modules, print_info
    print_info()
    
    print("\n选择示例:")
    print("1. 摄像头示例")
    print("2. Go2机器狗示例")
    print("3. ONNX推理示例")
    print("0. 退出")
    
    while True:
        try:
            choice = input("\n请输入选择 (0-3): ").strip()
            
            if choice == "0":
                print("退出")
                break
            elif choice == "1":
                example_camera()
            elif choice == "2":
                example_go2()
            elif choice == "3":
                example_onnx()
            else:
                print("无效选择，请重新输入")
                
        except KeyboardInterrupt:
            print("\n退出")
            break
        except Exception as e:
            print(f"示例执行出错: {e}")

if __name__ == "__main__":
    main()