#!/bin/bash
# 菲西尔咨询表单服务 - 快速部署脚本

set -e

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

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}菲西尔咨询表单服务 - 快速部署${NC}"
echo -e "${GREEN}========================================${NC}"

# 检查 Python 版本
echo -e "\n${YELLOW}[1/5] 检查 Python 环境...${NC}"
python3 --version || {
    echo -e "${RED}错误: 未找到 Python3${NC}"
    exit 1
}
echo -e "${GREEN}✓ Python 检查通过${NC}"

# 检查环境变量
echo -e "\n${YELLOW}[2/5] 检查环境变量...${NC}"

if [ ! -f .env ]; then
    echo -e "${YELLOW}未找到 .env 文件，创建示例...${NC}"
    cp .env.example .env
    echo -e "${YELLOW}请编辑 .env 文件填写配置${NC}"
    exit 1
fi

source .env

if [ -z "$FEISHU_APP_ID" ] || [ "$FEISHU_APP_ID" == "cli_xxx" ]; then
    echo -e "${RED}错误: 请在 .env 中配置 FEISHU_APP_ID${NC}"
    exit 1
fi

if [ -z "$FEISHU_BITABLE_APP_TOKEN" ] || [ "$FEISHU_BITABLE_APP_TOKEN" == "basxxx" ]; then
    echo -e "${RED}错误: 请在 .env 中配置 FEISHU_BITABLE_APP_TOKEN${NC}"
    exit 1
fi

echo -e "${GREEN}✓ 环境变量检查通过${NC}"

# 创建数据目录
echo -e "\n${YELLOW}[3/5] 创建数据目录...${NC}"
DATA_DIR="${DATA_DIR:-/opt/ai-landing/data}"
sudo mkdir -p "$DATA_DIR"
sudo chown $(whoami):$(whoami) "$DATA_DIR"
echo -e "${GREEN}✓ 数据目录创建成功: $DATA_DIR${NC}"

# 测试飞书连接
echo -e "\n${YELLOW}[4/5] 测试飞书连接...${NC}"
python3 -c "
from consult_service import ConsultService
service = ConsultService()
try:
    token = service.bitable_client.get_access_token()
    print('✓ 飞书连接测试成功')
except Exception as e:
    print(f'✗ 飞书连接失败: {e}')
    exit(1)
"

# 启动服务
echo -e "\n${YELLOW}[5/5] 启动服务...${NC}"
PORT="${PORT:-4001}"
echo -e "${GREEN}服务将在端口 $PORT 启动${NC}"
echo -e "${GREEN}API 端点: http://localhost:$PORT/api/consult${NC}"
echo -e "${GREEN}健康检查: http://localhost:$PORT/api/consult/health${NC}"

# 使用 nohup 后台运行
nohup python3 consult-service.py > service.log 2>&1 &
SERVICE_PID=$!

echo $SERVICE_PID > .service.pid

sleep 2

# 检查服务是否启动
if ps -p $SERVICE_PID > /dev/null; then
    echo -e "\n${GREEN}========================================${NC}"
    echo -e "${GREEN}✓ 服务启动成功！${NC}"
    echo -e "${GREEN}========================================${NC}"
    echo -e "进程 ID: $SERVICE_PID"
    echo -e "日志文件: service.log"
    echo -e "\n停止服务: kill \$(cat .service.pid)"
else
    echo -e "\n${RED}错误: 服务启动失败${NC}"
    echo -e "请查看日志: tail -f service.log"
    exit 1
fi

echo -e "\n${YELLOW}下一步操作：${NC}"
echo "1. 配置 Nginx 反向代理（可选）"
echo "2. 设置系统服务自动启动"
echo "3. 查看飞书多维表格配置指南: FEISHU_BITABLE_SETUP.md"
