import cv2
import sys
import platform

def list_available_cameras(max_test=10):
    """
    检测所有可用的相机设备
    """
    available_cameras = []
    
    print("=== 开始检测可用相机设备 ===")
    for i in range(max_test):
        # 根据操作系统选择不同的后端
        if platform.system() == "Windows":
            cap = cv2.VideoCapture(i, cv2.CAP_DSHOW)
        elif platform.system() == "Linux":
            cap = cv2.VideoCapture(i, cv2.CAP_V4L2)
        else:  # macOS
            cap = cv2.VideoCapture(i, cv2.CAP_AVFOUNDATION)
        
        if cap.isOpened():
            # 获取相机基本信息
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = cap.get(cv2.CAP_PROP_FPS)
            
            print(f"✅ 相机 {i}: 可用")
            available_cameras.append(i)
            cap.release()
        else:
            cap.release()
    
    print(f"检测完成，找到 {len(available_cameras)} 个可用相机: {available_cameras}")
    return available_cameras

def get_camera_properties(camera_index):
    """
    获取相机的基本属性和当前设置
    """
    if platform.system() == "Windows":
        cap = cv2.VideoCapture(camera_index, cv2.CAP_DSHOW)
    elif platform.system() == "Linux":
        cap = cv2.VideoCapture(camera_index, cv2.CAP_V4L2)
    else:
        cap = cv2.VideoCapture(camera_index, cv2.CAP_AVFOUNDATION)
    
    if not cap.isOpened():
        print(f"❌ 无法打开相机 {camera_index}")
        return None
    
    print(f"\n{'='*60}")
    print(f"相机 {camera_index} 详细信息")
    print(f"{'='*60}")
    
    # 相机基本属性列表 [5,8](@ref)
    properties = [
        (cv2.CAP_PROP_FRAME_WIDTH, "帧宽度"),
        (cv2.CAP_PROP_FRAME_HEIGHT, "帧高度"),
        (cv2.CAP_PROP_FPS, "帧率(FPS)"),
        (cv2.CAP_PROP_BRIGHTNESS, "亮度"),
        (cv2.CAP_PROP_CONTRAST, "对比度"),
        (cv2.CAP_PROP_SATURATION, "饱和度"),
        (cv2.CAP_PROP_HUE, "色调"),
        (cv2.CAP_PROP_GAIN, "增益"),
        (cv2.CAP_PROP_EXPOSURE, "曝光度"),
        (cv2.CAP_PROP_AUTO_EXPOSURE, "自动曝光"),
        (cv2.CAP_PROP_AUTOFOCUS, "自动对焦"),
        (cv2.CAP_PROP_FOCUS, "焦距"),
        (cv2.CAP_PROP_ZOOM, "变焦"),
        (cv2.CAP_PROP_WHITE_BALANCE_BLUE_U, "白平衡蓝色"),
        (cv2.CAP_PROP_WHITE_BALANCE_RED_V, "白平衡红色"),
        (cv2.CAP_PROP_BACKLIGHT, "背光补偿"),
        (cv2.CAP_PROP_BUFFERSIZE, "缓冲区大小"),
    ]
    
    # 打印各属性当前值
    print("📊 当前参数设置:")
    for prop_id, prop_name in properties:
        value = cap.get(prop_id)
        # 特殊处理曝光属性（可能为负值）
        if prop_id == cv2.CAP_PROP_EXPOSURE:
            if value < 0:
                print(f"   {prop_name}: 自动曝光")
            else:
                print(f"   {prop_name}: {value}")
        else:
            print(f"   {prop_name}: {value}")
    
    return cap

def test_supported_resolutions(cap, camera_index):
    """
    测试相机支持的分辨率 [5,6](@ref)
    """
    print(f"\n🔍 测试相机 {camera_index} 支持的分辨率:")
    
    # 常见分辨率列表
    common_resolutions = [
        (160, 120),    # QQVGA
        (320, 240),    # QVGA
        (640, 480),    # VGA
        (800, 600),    # SVGA
        (1024, 768),   # XGA
        (1280, 720),   # 720p HD
        (1280, 800),   # WXGA
        (1366, 768),   # HD
        (1920, 1080),  # 1080p Full HD
        (2560, 1440),  # 2K
        (3840, 2160),  # 4K UHD
    ]
    
    supported_resolutions = []
    
    for width, height in common_resolutions:
        # 尝试设置分辨率
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        
        # 读取实际设置的分辨率
        actual_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        actual_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        
        # 检查是否设置成功
        if actual_width == width and actual_height == height:
            supported_resolutions.append((width, height))
            print(f"   ✅ {width}x{height}")
        else:
            print(f"   ❌ {width}x{height} (实际: {actual_width}x{actual_height})")
    
    return supported_resolutions

def test_supported_fps(cap, camera_index, test_width=640, test_height=480):
    """
    测试相机支持的帧率范围 [10](@ref)
    """
    print(f"\n🎬 测试相机 {camera_index} 支持的帧率 (分辨率: {test_width}x{test_height}):")
    
    # 设置测试分辨率
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, test_width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, test_height)
    
    test_fps_values = [15, 24, 25, 30, 48, 50, 60, 90, 120]
    supported_fps = []
    
    for fps in test_fps_values:
        # 尝试设置帧率
        if cap.set(cv2.CAP_PROP_FPS, fps):
            actual_fps = cap.get(cv2.CAP_PROP_FPS)
            # 允许一定的误差
            if abs(actual_fps - fps) <= 1.0:
                supported_fps.append(fps)
                print(f"   ✅ {fps} FPS")
            else:
                print(f"   ⚠️  {fps} FPS (实际: {actual_fps:.1f} FPS)")
        else:
            print(f"   ❌ {fps} FPS")
    
    return supported_fps

def get_camera_backend_info(cap, camera_index):
    """
    获取相机后端信息 [1,8](@ref)
    """
    try:
        # 尝试获取后端名称（某些OpenCV版本支持）
        backend_name = str(cap.getBackendName()) if hasattr(cap, 'getBackendName') else "未知"
        
        # 根据后端判断相机类型
        if "rtsp" in backend_name.lower() or "ffmpeg" in backend_name.lower():
            camera_type = "网络相机"
        else:
            camera_type = "物理相机"
        
        print(f"\n🔧 相机 {camera_index} 后端信息:")
        print(f"   后端类型: {backend_name}")
        print(f"   相机类型: {camera_type}")
        
        return backend_name, camera_type
    except:
        print(f"\n🔧 相机 {camera_index} 后端信息: 无法获取")
        return "未知", "未知"

def main():
    """
    主函数
    """
    print("📷 OpenCV相机信息检测工具")
    print("=" * 50)
    
    # 检查OpenCV版本
    print(f"OpenCV版本: {cv2.__version__}")
    print(f"Python版本: {sys.version}")
    print(f"操作系统: {platform.system()} {platform.release()}")
    
    # 1. 检测可用相机
    available_cameras = list_available_cameras()
    
    if not available_cameras:
        print("❌ 未找到任何可用的相机设备")
        return
    
    # 2. 为每个相机获取详细信息
    for camera_index in available_cameras:
        cap = get_camera_properties(camera_index)
        if cap is None:
            continue
        
        # 获取后端信息
        backend_name, camera_type = get_camera_backend_info(cap, camera_index)
        
        # 测试支持的分辨率
        supported_res = test_supported_resolutions(cap, camera_index)
        
        # 测试支持的帧率（使用VGA分辨率进行测试）
        supported_fps = test_supported_fps(cap, camera_index, 640, 480)
        
        # 恢复默认设置
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        cap.set(cv2.CAP_PROP_FPS, 30)
        
        # 释放相机资源
        cap.release()
        
        print(f"\n📋 相机 {camera_index} 支持汇总:")
        print(f"   分辨率: {len(supported_res)} 种")
        for res in supported_res:
            print(f"     - {res[0]}x{res[1]}")
        print(f"   帧率: {supported_fps}")
        print(f"   类型: {camera_type}")
        print(f"{'='*60}\n")

if __name__ == "__main__":
    main()