#!/bin/bash

# 数据库迁移脚本
# 用于创建模板市场相关的数据库表

echo "=========================================="
echo "执行数据库迁移 - 模板市场"
echo "=========================================="
echo ""

# 数据库连接信息（从config.py中获取）
DB_HOST="gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com"
DB_PORT="24936"
DB_USER="root"
DB_NAME="agent_db"
SQL_FILE="backend/create_template_market_tables.sql"

# 检查SQL文件是否存在
if [ ! -f "$SQL_FILE" ]; then
    echo "❌ SQL文件不存在: $SQL_FILE"
    exit 1
fi

echo "📄 SQL文件: $SQL_FILE"
echo "🔗 数据库: $DB_NAME @ $DB_HOST:$DB_PORT"
echo ""

# 检查mysql命令是否可用
if ! command -v mysql &> /dev/null; then
    echo "⚠️  mysql命令不可用，请手动执行SQL脚本"
    echo ""
    echo "手动执行步骤："
    echo "1. 连接到数据库："
    echo "   mysql -h $DB_HOST -P $DB_PORT -u $DB_USER -p $DB_NAME"
    echo ""
    echo "2. 执行SQL："
    echo "   source $(pwd)/$SQL_FILE;"
    echo ""
    exit 1
fi

# 提示输入密码
echo "请输入数据库密码："
read -s DB_PASSWORD

echo ""
echo "正在执行SQL脚本..."
echo ""

# 执行SQL脚本
mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" < "$SQL_FILE"

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ 数据库迁移完成！"
    echo ""
    echo "📊 验证表是否创建："
    mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" "$DB_NAME" -e "SHOW TABLES LIKE 'workflow_template%'; SHOW TABLES LIKE 'template_%';"
else
    echo ""
    echo "❌ 数据库迁移失败，请检查错误信息"
    exit 1
fi
