#!/bin/bash
# 本地 MySQL 建库脚本：创建 allm，root 密码 yingping
# 连接串：mysql+aiomysql://root:yingping@localhost:3306/allm?charset=utf8mb4
#
# 使用前请确保 MySQL 已安装并启动：
#   macOS: brew install mysql && brew services start mysql
#   Ubuntu: sudo apt install mysql-server && sudo systemctl start mysql

set -e

DB_NAME="allm"
DB_USER="root"
DB_PASS="yingping"
HOST="127.0.0.1"
PORT="3306"

echo ">>> 检查 MySQL 是否可连接 (${HOST}:${PORT}) ..."

# 尝试无密码连接（首次安装）
if mysql -u "$DB_USER" -h "$HOST" -P "$PORT" -e "SELECT 1" 2>/dev/null; then
  echo ">>> 使用 root 无密码连接成功，创建库并设置密码..."
  mysql -u "$DB_USER" -h "$HOST" -P "$PORT" -e "
    CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    ALTER USER 'root'@'localhost' IDENTIFIED BY '${DB_PASS}';
    ALTER USER 'root'@'127.0.0.1' IDENTIFIED BY '${DB_PASS}';
    FLUSH PRIVILEGES;
  "
  echo ">>> 数据库 ${DB_NAME} 已创建，root 密码已设为 ${DB_PASS}"
# 尝试使用 yingping 连接（可能已设置过）
elif mysql -u "$DB_USER" -p"${DB_PASS}" -h "$HOST" -P "$PORT" -e "SELECT 1" 2>/dev/null; then
  echo ">>> 使用 root:yingping 连接成功，确保库存在..."
  mysql -u "$DB_USER" -p"${DB_PASS}" -h "$HOST" -P "$PORT" -e "
    CREATE DATABASE IF NOT EXISTS \`${DB_NAME}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
  "
  echo ">>> 数据库 ${DB_NAME} 已就绪"
else
  echo ">>> 无法连接 MySQL。请先安装并启动，且能以 root 登录（无密码或已知密码）。"
  echo ">>> 手动执行："
  echo "    mysql -u root -p -e \"CREATE DATABASE IF NOT EXISTS ${DB_NAME} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; ALTER USER 'root'@'localhost' IDENTIFIED BY '${DB_PASS}'; FLUSH PRIVILEGES;\""
  exit 1
fi

echo ""
echo ">>> 在 .env 中设置："
echo "DATABASE_URL=mysql+aiomysql://${DB_USER}:${DB_PASS}@localhost:${PORT}/${DB_NAME}?charset=utf8mb4"
echo ""
echo ">>> 然后执行迁移："
echo "DATABASE_URL=\"mysql+aiomysql://${DB_USER}:${DB_PASS}@localhost:${PORT}/${DB_NAME}?charset=utf8mb4\" python -m alembic upgrade head"
