#!/bin/bash
# 快速部署脚本 - 考陪练 SQL 执行器
# 使用方法: bash quick_deploy.sh

set -e  # 遇到错误立即退出

echo "==================================="
echo "考陪练 SQL 执行器快速部署脚本"
echo "服务器: 120.79.247.16"
echo "==================================="

# 配置变量
APP_DIR="/opt/kaopeilian/backend"
SERVICE_NAME="kaopeilian-backend"
PYTHON_VERSION="python3"

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

# 打印带颜色的信息
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

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

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

# 检查是否为 root 用户
if [[ $EUID -ne 0 ]]; then
   print_error "此脚本必须以 root 用户运行"
   exit 1
fi

# 1. 安装系统依赖
print_info "安装系统依赖..."
apt update
apt install -y python3 python3-pip python3-venv git mysql-client

# 2. 创建应用目录
print_info "创建应用目录..."
mkdir -p $APP_DIR

# 3. 检查代码是否存在
if [ ! -f "$APP_DIR/app/main.py" ]; then
    print_warning "代码不存在，请先上传代码到 $APP_DIR"
    print_info "可以使用以下命令上传："
    echo "scp -r /path/to/kaopeilian-backend/* root@120.79.247.16:$APP_DIR/"
    exit 1
fi

cd $APP_DIR

# 4. 创建虚拟环境
print_info "创建 Python 虚拟环境..."
if [ ! -d "venv" ]; then
    $PYTHON_VERSION -m venv venv
fi

# 5. 激活虚拟环境并安装依赖
print_info "安装 Python 依赖..."
source venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

# 6. 创建环境配置文件
if [ ! -f ".env" ]; then
    print_info "创建环境配置文件..."
    cat > .env << EOF
# 应用配置
APP_NAME=KaoPeiLian
DEBUG=False
HOST=0.0.0.0
PORT=8000

# 数据库配置
DATABASE_URL=mysql+aiomysql://root:Kaopeilian2025!@#@localhost:3306/kaopeilian?charset=utf8mb4

# Redis配置
REDIS_URL=redis://localhost:6379/0

# JWT配置
SECRET_KEY=production-secret-key-for-kaopeilian-2025-at-least-32-chars
ALGORITHM=HS256
ACCESS_TOKEN_EXPIRE_MINUTES=30

# CORS配置
CORS_ORIGINS=["http://120.79.247.16:8000", "http://aiedu.ireborn.com.cn", "http://localhost:3000"]

# 日志配置
LOG_LEVEL=INFO
LOG_FORMAT=json
EOF
    print_info "环境配置文件已创建"
else
    print_warning "环境配置文件已存在，跳过创建"
fi

# 7. 创建 systemd 服务
print_info "配置 systemd 服务..."
cat > /etc/systemd/system/${SERVICE_NAME}.service << EOF
[Unit]
Description=KaoPeiLian Backend API
After=network.target mysql.service

[Service]
Type=simple
User=root
WorkingDirectory=$APP_DIR
Environment="PATH=$APP_DIR/venv/bin"
Environment="PYTHONPATH=$APP_DIR"
ExecStart=$APP_DIR/venv/bin/uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 2
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

# 8. 重新加载 systemd 并启动服务
print_info "启动服务..."
systemctl daemon-reload
systemctl enable ${SERVICE_NAME}

# 检查服务是否已经运行
if systemctl is-active --quiet ${SERVICE_NAME}; then
    print_info "重启服务..."
    systemctl restart ${SERVICE_NAME}
else
    print_info "启动服务..."
    systemctl start ${SERVICE_NAME}
fi

# 9. 等待服务启动
print_info "等待服务启动..."
sleep 5

# 10. 检查服务状态
if systemctl is-active --quiet ${SERVICE_NAME}; then
    print_info "服务启动成功！"
else
    print_error "服务启动失败，请检查日志"
    journalctl -u ${SERVICE_NAME} -n 50
    exit 1
fi

# 11. 配置防火墙
print_info "配置防火墙..."
if command -v ufw &> /dev/null; then
    ufw allow 8000/tcp
    ufw --force enable
elif command -v firewall-cmd &> /dev/null; then
    firewall-cmd --permanent --add-port=8000/tcp
    firewall-cmd --reload
else
    print_warning "未检测到防火墙，请手动配置端口 8000"
fi

# 12. 测试部署
print_info "测试部署..."
sleep 2

# 健康检查
if curl -s http://localhost:8000/health > /dev/null; then
    print_info "健康检查通过 ✓"
else
    print_error "健康检查失败"
fi

# 测试 SQL 执行器
print_info "测试 SQL 执行器..."
RESPONSE=$(curl -s -X POST http://localhost:8000/api/v1/sql/execute-simple \
  -H "X-API-Key: dify-2025-kaopeilian" \
  -H "Content-Type: application/json" \
  -d '{"sql": "SELECT COUNT(*) as total FROM users"}')

if [[ $RESPONSE == *"SQL 执行成功"* ]]; then
    print_info "SQL 执行器测试通过 ✓"
    echo "响应: $RESPONSE"
else
    print_error "SQL 执行器测试失败"
    echo "响应: $RESPONSE"
fi

# 13. 打印部署信息
echo ""
echo "==================================="
echo -e "${GREEN}部署完成！${NC}"
echo "==================================="
echo ""
echo "服务信息："
echo "- 服务状态: $(systemctl is-active ${SERVICE_NAME})"
echo "- API 地址: http://120.79.247.16:8000"
echo "- 健康检查: http://120.79.247.16:8000/health"
echo "- SQL 执行器: http://120.79.247.16:8000/api/v1/sql/execute-simple"
echo ""
echo "认证信息："
echo "- API Key: dify-2025-kaopeilian"
echo "- 请求头: X-API-Key"
echo ""
echo "常用命令："
echo "- 查看日志: journalctl -u ${SERVICE_NAME} -f"
echo "- 重启服务: systemctl restart ${SERVICE_NAME}"
echo "- 停止服务: systemctl stop ${SERVICE_NAME}"
echo "- 服务状态: systemctl status ${SERVICE_NAME}"
echo ""
echo "Dify 配置："
echo "1. 鉴权类型: 请求头"
echo "2. 鉴权头部前缀: Custom"
echo "3. 键: X-API-Key"
echo "4. 值: dify-2025-kaopeilian"
echo "==================================="#


