#!/bin/bash
# InsightFlow Phase 3 部署脚本

set -e

echo "🚀 InsightFlow Phase 3 部署脚本"
echo "================================"

# 检查环境
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

if ! command -v git &> /dev/null; then
    echo "❌ Git 未安装，请先安装 Git"
    exit 1
fi

# 配置
IMAGE_NAME="insightflow"
IMAGE_TAG="phase3"
CONTAINER_NAME="insightflow-app"
PORT="18000"
DATA_DIR="/opt/data/insightflow"

# 检查环境变量
if [ -z "$KIMI_API_KEY" ]; then
    echo "⚠️  警告: KIMI_API_KEY 未设置"
fi

if [ -z "$ALIYUN_ACCESS_KEY_ID" ]; then
    echo "⚠️  警告: ALIYUN_ACCESS_KEY_ID 未设置"
fi

if [ -z "$ALIYUN_ACCESS_KEY_SECRET" ]; then
    echo "⚠️  警告: ALIYUN_ACCESS_KEY_SECRET 未设置"
fi

echo ""
echo "📦 构建 Docker 镜像..."
docker build -t ${IMAGE_NAME}:${IMAGE_TAG} .

echo ""
echo "🛑 停止旧容器..."
docker stop ${CONTAINER_NAME} 2>/dev/null || true
docker rm ${CONTAINER_NAME} 2>/dev/null || true

echo ""
echo "📁 创建数据目录..."
mkdir -p ${DATA_DIR}

echo ""
echo "🚀 启动新容器..."
docker run -d \
  --name ${CONTAINER_NAME} \
  -p ${PORT}:8000 \
  -v ${DATA_DIR}:/app/data \
  -e KIMI_API_KEY="${KIMI_API_KEY}" \
  -e KIMI_BASE_URL="${KIMI_BASE_URL:-https://api.kimi.com/coding}" \
  -e ALIYUN_ACCESS_KEY_ID="${ALIYUN_ACCESS_KEY_ID}" \
  -e ALIYUN_ACCESS_KEY_SECRET="${ALIYUN_ACCESS_KEY_SECRET}" \
  -e DB_PATH="/app/data/insightflow.db" \
  --restart unless-stopped \
  ${IMAGE_NAME}:${IMAGE_TAG}

echo ""
echo "⏳ 等待服务启动..."
sleep 3

echo ""
echo "✅ 部署完成！"
echo ""
echo "📊 服务状态:"
docker ps --filter "name=${CONTAINER_NAME}" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"

echo ""
echo "🔗 访问地址: http://localhost:${PORT}"
echo "📋 查看日志: docker logs -f ${CONTAINER_NAME}"
echo ""
