#!/bin/bash

echo "=== macOS 麦克风权限诊断和修复工具 ==="
echo "当前时间: $(date)"
echo "用户: $(whoami)"
echo ""

# 1. 检查音频设备
echo "📱 1. 音频设备检查"
echo "----------------------------------------"
system_profiler SPAudioDataType | grep -E "(MacBook Pro|Built-in|Microphone)" || echo "未找到内置麦克风设备"
echo ""

# 2. 检查麦克风权限状态
echo "🔐 2. 麦克风权限状态检查"
echo "----------------------------------------"
# 尝试读取TCC数据库
if [ -f ~/Library/Application\ Support/com.apple.TCC/TCC.db ]; then
    echo "TCC数据库存在，检查权限记录..."
    sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db \
        "SELECT client, auth_value, auth_reason FROM access WHERE service='kTCCServiceMicrophone';" 2>/dev/null | \
        while IFS='|' read -r client auth_value auth_reason; do
            if [ ! -z "$client" ]; then
                status="未知"
                case $auth_value in
                    0) status="拒绝" ;;
                    1) status="允许" ;;
                    2) status="允许" ;;
                    3) status="限制" ;;
                esac
                echo "应用: $client -> 权限: $status ($auth_value)"
            fi
        done
else
    echo "TCC数据库不存在或无法访问"
fi
echo ""

# 3. 测试系统音频录制能力
echo "🎤 3. 系统音频录制测试"
echo "----------------------------------------"
if command -v sox >/dev/null 2>&1; then
    echo "使用sox进行录制测试..."
    timeout 2s rec -q -t wav /tmp/test_audio_$(date +%s).wav 2>/dev/null
    if [ $? -eq 0 ] && [ -f /tmp/test_audio_*.wav ]; then
        audio_file=$(ls /tmp/test_audio_*.wav | head -1)
        file_size=$(stat -f%z "$audio_file" 2>/dev/null || echo "0")
        echo "✅ 录制成功！文件大小: ${file_size} 字节"
        rm -f /tmp/test_audio_*.wav
    else
        echo "❌ 录制失败 - 可能是权限问题"
    fi
else
    echo "⚠️  sox未安装，跳过录制测试"
    echo "   可以通过 'brew install sox' 安装"
fi
echo ""

# 4. 检查Qt程序的权限状态
echo "🖥️  4. Qt程序权限检查"
echo "----------------------------------------"
qt_app_path="./cmake-build-debug/qt_speech_simple"
if [ -f "$qt_app_path" ]; then
    echo "Qt程序路径: $qt_app_path"
    
    # 检查程序是否在TCC数据库中
    app_bundle_id=$(basename "$qt_app_path")
    echo "检查程序ID: $app_bundle_id"
    
    # 尝试查找相关权限记录
    sqlite3 ~/Library/Application\ Support/com.apple.TCC/TCC.db \
        "SELECT client, auth_value FROM access WHERE service='kTCCServiceMicrophone' AND client LIKE '%$app_bundle_id%';" 2>/dev/null | \
        while IFS='|' read -r client auth_value; do
            if [ ! -z "$client" ]; then
                status="拒绝"
                [ "$auth_value" = "2" ] && status="允许"
                echo "找到权限记录: $client -> $status"
            fi
        done
else
    echo "❌ Qt程序不存在: $qt_app_path"
fi
echo ""

# 5. 权限修复建议
echo "🔧 5. 权限修复步骤"
echo "----------------------------------------"
echo "如果遇到权限问题，请按以下步骤操作："
echo ""
echo "方法1: 通过系统设置授予权限"
echo "  1. 打开 系统设置 (System Preferences)"
echo "  2. 点击 安全性与隐私 (Security & Privacy)"
echo "  3. 选择 隐私 (Privacy) 标签"
echo "  4. 在左侧列表中选择 麦克风 (Microphone)"
echo "  5. 确保Qt程序已勾选并允许访问麦克风"
echo ""
echo "方法2: 重置麦克风权限 (需要管理员权限)"
echo "  sudo tccutil reset Microphone"
echo "  然后重新运行Qt程序，会再次弹出权限请求"
echo ""
echo "方法3: 手动添加权限 (macOS Monterey及以上)"
echo "  1. 系统设置 -> 隐私与安全性 -> 麦克风"
echo "  2. 点击 + 号添加应用程序"
echo "  3. 选择Qt程序可执行文件"
echo ""

# 6. 启动Qt程序进行实际测试
echo "🚀 6. 启动Qt程序测试"
echo "----------------------------------------"
if [ -f "$qt_app_path" ]; then
    echo "即将启动Qt程序进行麦克风权限测试..."
    echo "请注意观察是否弹出权限请求对话框"
    echo "如果弹出，请点击 '允许' 或 'Allow'"
    echo ""
    echo "按回车键继续启动程序，或Ctrl+C取消..."
    read -r
    
    echo "启动程序: $qt_app_path"
    cd cmake-build-debug && ./qt_speech_simple
else
    echo "❌ 程序文件不存在，请先编译项目"
    echo "运行: mkdir -p cmake-build-debug && cd cmake-build-debug && cmake .. && make"
fi