#!/bin/bash

cd "$(dirname "$0")"

echo "========================================"
echo "   NOFX 数据库清理工具"
echo "========================================"
echo ""

show_menu() {
    echo "请选择操作:"
    echo ""
    echo "[1] 清理脏数据 (保留有效配置)"
    echo "[2] 完全重置数据库 (删除所有数据)"
    echo "[3] 查看当前配置状态"
    echo "[0] 退出"
    echo ""
}

clean_data() {
    echo ""
    echo "🧹 开始清理脏数据..."
    go run clean_config_data.go
    echo ""
    read -p "按回车继续..."
}

reset_database() {
    echo ""
    echo "⚠️  警告: 此操作将删除所有配置数据！"
    read -p "确认要继续吗? (y/N): " confirm
    
    if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
        echo "已取消"
        echo ""
        read -p "按回车继续..."
        return
    fi
    
    echo ""
    echo "🗑️  正在删除数据库文件..."
    cd ..
    if [ -f "config.db" ]; then
        rm -f config.db
        echo "✅ 数据库已删除"
    else
        echo "⚠️  数据库文件不存在"
    fi
    echo ""
    echo "💡 提示: 重启服务后将自动创建新数据库"
    echo ""
    read -p "按回车继续..."
    cd scripts
}

show_status() {
    echo ""
    echo "📊 查询当前配置状态..."
    
    sqlite3 ../config.db <<EOF
.mode column
.headers on
SELECT 'AI模型总数' as Type, COUNT(*) as Count FROM ai_models
UNION ALL
SELECT '  - 有效配置', COUNT(*) FROM ai_models WHERE enabled = 1 AND api_key != ''
UNION ALL
SELECT '交易所总数', COUNT(*) FROM exchanges
UNION ALL
SELECT '  - 有效配置', COUNT(*) FROM exchanges WHERE enabled = 1 AND api_key != ''
UNION ALL
SELECT '交易员总数', COUNT(*) FROM traders;
EOF
    
    echo ""
    read -p "按回车继续..."
}

while true; do
    clear
    echo "========================================"
    echo "   NOFX 数据库清理工具"
    echo "========================================"
    echo ""
    show_menu
    read -p "请输入选项 [0-3]: " choice
    
    case $choice in
        1)
            clean_data
            ;;
        2)
            reset_database
            ;;
        3)
            show_status
            ;;
        0)
            echo ""
            echo "再见！"
            exit 0
            ;;
        *)
            echo "无效选项，请重新选择"
            sleep 1
            ;;
    esac
done
