#!/bin/bash
#
# OpenClaw 自动化安装脚本 - macOS/Linux 入口 (带验证码验证)
# 域名: alphamarket.com.cn
# 使用: curl -fsSL https://alphamarket.com.cn/install | bash
#

set -e

# 颜色定义
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"
}

# 验证验证码
verify_code() {
    local code="$1"
    local verify_url="https://alphamarket.com.cn/api/verify"
    
    # 使用 curl 验证验证码
    local response=$(curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"code\": \"$code\"}" \
        "$verify_url" 2>/dev/null)
    
    # 检查验证结果
    if echo "$response" | grep -q '"valid":true'; then
        return 0
    else
        return 1
    fi
}

# 提示输入验证码
prompt_verification_code() {
    echo ""
    echo "========================================"
    echo "   安全验证"
    echo "========================================"
    echo ""
    echo "此脚本需要授权验证码才能运行。"
    echo "请联系管理员获取有效验证码。"
    echo ""
    
    local attempts=0
    local max_attempts=3
    
    while [ $attempts -lt $max_attempts ]; do
        echo -n "请输入24位验证码: "
        read -r code
        
        # 基本格式检查
        if [ ${#code} -ne 24 ]; then
            print_error "验证码必须是24位字符"
            attempts=$((attempts + 1))
            echo ""
            continue
        fi
        
        print_info "正在验证..."
        
        if verify_code "$code"; then
            print_success "验证通过！"
            echo ""
            return 0
        else
            print_error "验证失败：验证码无效、已过期或已被使用"
            attempts=$((attempts + 1))
            remaining=$((max_attempts - attempts))
            if [ $remaining -gt 0 ]; then
                echo "还剩 $remaining 次尝试机会"
            fi
            echo ""
        fi
    done
    
    print_error "验证失败次数过多，安装终止"
    exit 1
}

# 显示欢迎信息
print_welcome() {
    echo ""
    echo "========================================"
    echo "   OpenClaw 自动安装程序"
    echo "   alphamarket.com.cn"
    echo "========================================"
    echo ""
}

# 检测操作系统
detect_os() {
    OS=$(uname -s)
    ARCH=$(uname -m)
    
    case "$OS" in
        Darwin)
            PLATFORM="darwin"
            ;;
        Linux)
            PLATFORM="linux"
            ;;
        *)
            print_error "不支持的操作系统: $OS"
            print_error "仅支持 macOS 和 Linux"
            exit 1
            ;;
    esac
    
    # 检测架构
    case "$ARCH" in
        x86_64|amd64)
            ARCH="x64"
            ;;
        arm64|aarch64)
            ARCH="arm64"
            ;;
        *)
            print_warning "未知的架构: $ARCH，尝试使用 x64"
            ARCH="x64"
            ;;
    esac
    
    print_info "检测到系统: $OS ($ARCH)"
}

# 下载并执行对应脚本
download_and_run() {
    local script_url="https://alphamarket.com.cn/scripts/install-${PLATFORM}.sh"
    local temp_script=$(mktemp)
    
    print_info "正在下载安装脚本..."
    
    if command -v curl &> /dev/null; then
        curl -fsSL "$script_url" -o "$temp_script"
    elif command -v wget &> /dev/null; then
        wget -q "$script_url" -O "$temp_script"
    else
        print_error "需要 curl 或 wget 来下载安装脚本"
        exit 1
    fi
    
    if [ ! -s "$temp_script" ]; then
        print_error "下载脚本失败，请检查网络连接"
        rm -f "$temp_script"
        exit 1
    fi
    
    chmod +x "$temp_script"
    
    print_info "开始安装..."
    bash "$temp_script" "$ARCH"
    
    rm -f "$temp_script"
}

# 主函数
main() {
    print_welcome
    prompt_verification_code
    detect_os
    download_and_run
    print_success "安装完成！"
}

main "$@"
