#!/bin/bash

# QSmartAssistant 语音测试工具构建脚本

set -e  # 遇到错误时退出

echo "=== QSmartAssistant 语音测试工具构建脚本 ==="

# 检查是否在正确的目录
if [ ! -f "CMakeLists.txt" ]; then
    echo "错误: 请在项目根目录运行此脚本"
    exit 1
fi

# 创建构建目录
BUILD_DIR="build"
if [ -d "$BUILD_DIR" ]; then
    echo "清理现有构建目录..."
    rm -rf "$BUILD_DIR"
fi

echo "创建构建目录: $BUILD_DIR"
mkdir -p "$BUILD_DIR"
cd "$BUILD_DIR"

# 检查Qt6
echo "检查Qt6安装..."
if ! command -v qmake6 &> /dev/null && ! command -v qmake &> /dev/null; then
    echo "警告: 未找到Qt6，请确保已正确安装Qt6"
fi

# 配置CMake
echo "配置CMake..."
if [ -n "$SHERPA_ONNX_ROOT" ]; then
    echo "使用自定义sherpa-onnx路径: $SHERPA_ONNX_ROOT"
    cmake -DSHERPA_ONNX_ROOT="$SHERPA_ONNX_ROOT" ..
else
    echo "使用默认sherpa-onnx路径"
    cmake ..
fi

# 编译
echo "开始编译..."
CPU_COUNT=$(sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null || echo 4)
make -j$CPU_COUNT

# 检查编译结果
if [ -f "qt_speech_simple" ]; then
    echo "=== 编译成功! ==="
    echo "可执行文件位置: $(pwd)/qt_speech_simple"
    echo ""
    echo "运行程序:"
    echo "  cd $(pwd)"
    echo "  ./qt_speech_simple"
    echo ""
    echo "注意: 请确保模型文件已正确放置在 ~/.config/QSmartAssistant/Data/ 目录下"
else
    echo "=== 编译失败! ==="
    echo "请检查错误信息并解决依赖问题"
    exit 1
fi