#!/bin/bash

# 手部检测Web服务启动脚本
# 包含虚拟环境激活和服务启动

# 设置脚本目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印彩色消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 显示标题
echo "================================================"
echo "    🤖 手部检测Web服务启动器"
echo "================================================"
echo ""

# 检查Python3是否存在
if ! command -v python3 &> /dev/null; then
    print_error "Python3 未找到，请先安装Python3"
    exit 1
fi

print_info "Python3 版本: $(python3 --version)"

# 检查虚拟环境是否存在
if [ ! -d "venv" ]; then
    print_warning "虚拟环境不存在，正在创建..."
    python3 -m venv venv
    if [ $? -eq 0 ]; then
        print_success "虚拟环境创建成功"
    else
        print_error "虚拟环境创建失败"
        exit 1
    fi
fi

# 激活虚拟环境
print_info "正在激活虚拟环境..."
source venv/bin/activate

if [ $? -eq 0 ]; then
    print_success "虚拟环境已激活"
else
    print_error "虚拟环境激活失败"
    exit 1
fi

# 检查依赖是否已安装
print_info "检查Python依赖..."
if [ -f "requirements.txt" ]; then
    # 检查是否需要安装依赖
    if ! python -c "import flask, flask_socketio, cv2, mediapipe" &> /dev/null; then
        print_warning "依赖未完全安装，正在安装..."
        # 先强制降级 numpy，避免 numpy 2.x 兼容性问题
        pip install --break-system-packages --force-reinstall 'numpy<2'
        pip install --break-system-packages -r requirements.txt
        if [ $? -eq 0 ]; then
            print_success "依赖安装成功"
        else
            print_error "依赖安装失败"
            exit 1
        fi
    else
        print_success "依赖已安装"
    fi
else
    print_error "requirements.txt 文件不存在"
    exit 1
fi

# 检查必要文件是否存在
print_info "检查必要文件..."
required_files=("run_web_service.py" "src/web_server.py" "src/hand_detection_3d.py" "templates/index.html")
for file in "${required_files[@]}"; do
    if [ ! -f "$file" ]; then
        print_error "缺少必要文件: $file"
        exit 1
    fi
done
print_success "所有必要文件存在"

# 解析命令行参数
HOST="0.0.0.0"
PORT="5000"
DEBUG=""
TEST_VIDEO=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --host)
            HOST="$2"
            shift 2
            ;;
        --port)
            PORT="$2"
            shift 2
            ;;
        --debug)
            DEBUG="--debug"
            shift
            ;;
        --test-video)
            TEST_VIDEO="--test-video $2"
            shift 2
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo ""
            echo "选项:"
            echo "  --host HOST          服务器地址 (默认: 0.0.0.0)"
            echo "  --port PORT          端口号 (默认: 5000)"
            echo "  --debug              启用调试模式"
            echo "  --test-video VIDEO   使用本地测试视频"
            echo "  -h, --help           显示帮助信息"
            echo ""
            echo "示例:"
            echo "  $0                                    # 基本启动"
            echo "  $0 --host localhost --port 8080      # 自定义地址和端口"
            echo "  $0 --debug                            # 调试模式"
            echo "  $0 --test-video data/videos/test.mp4  # 本地视频测试"
            exit 0
            ;;
        *)
            print_error "未知参数: $1"
            echo "使用 $0 --help 查看帮助"
            exit 1
            ;;
    esac
done

# 显示启动信息
echo ""
print_info "启动配置:"
echo "  - 服务器地址: $HOST"
echo "  - 端口号: $PORT"
if [ ! -z "$DEBUG" ]; then
    echo "  - 调试模式: 启用"
fi
if [ ! -z "$TEST_VIDEO" ]; then
    echo "  - 测试视频: ${TEST_VIDEO#--test-video }"
fi
echo ""

# 显示访问地址
if [ "$HOST" = "0.0.0.0" ]; then
    print_info "服务启动后可通过以下地址访问:"
    echo "  - 本地访问: http://localhost:$PORT"
    echo "  - 局域网访问: http://$(hostname -I | awk '{print $1}'):$PORT"
else
    print_info "服务启动后访问地址: http://$HOST:$PORT"
fi

echo ""
print_info "按 Ctrl+C 停止服务"
echo "================================================"
echo ""

# 启动服务
print_info "正在启动手部检测Web服务..."
python3 run_web_service.py --host "$HOST" --port "$PORT" $DEBUG $TEST_VIDEO