#!/bin/bash
# 本地验证 goosed Docker 镜像构建 & 运行
# 用法: bash scripts/verify-goosed-docker.sh [tag]

set -euo pipefail

TAG="${1:-local}"
IMAGE_NAME="tkmind/goosed:${TAG}"
CONTAINER_NAME="goosed-test-$$"
PORT=${GOOSE_PORT:-18006}
SECRET_KEY="${GOOSE_SERVER__SECRET_KEY:-test-secret-key-$(date +%s)}"

echo "=== Goosed Docker 镜像验证 ==="
echo "Image: $IMAGE_NAME"
echo "Port: $PORT"
echo ""

cleanup() {
  echo "🧹 清理测试容器..."
  docker rm -f "$CONTAINER_NAME" 2>/dev/null || true
  docker volume rm goosed-test-$$-data 2>/dev/null || true
}

trap cleanup EXIT

# 1. 构建镜像（如果是 local 标签）
if [[ "$TAG" == "local" ]]; then
  echo "📦 Step 1: 构建 Docker 镜像..."
  docker build \
    -f tkmind_go/Dockerfile.goosed \
    -t "$IMAGE_NAME" \
    tkmind_go/
  echo "✅ 镜像构建完成"
else
  echo "📥 Step 1: 拉取远程镜像..."
  docker pull "$IMAGE_NAME"
  echo "✅ 镜像拉取完成"
fi

echo ""
echo "🚀 Step 2: 启动容器..."

# 2. 创建数据卷
docker volume create "goosed-test-$$-data" || true

# 3. 启动容器
docker run -d \
  --name "$CONTAINER_NAME" \
  -p "${PORT}:18006" \
  -e GOOSE_HOST=0.0.0.0 \
  -e GOOSE_PORT=18006 \
  -e "GOOSE_SERVER__SECRET_KEY=${SECRET_KEY}" \
  -v "goosed-test-$$-data:/home/goose/.local/share/goose" \
  "$IMAGE_NAME" \
  agent

echo "✅ 容器已启动: $CONTAINER_NAME (PID: $(docker inspect -f '{{.State.Pid}}' "$CONTAINER_NAME"))"

# 4. 等待容器就绪
echo ""
echo "⏳ Step 3: 等待容器就绪（最多 30 秒）..."
for i in {1..30}; do
  if docker exec "$CONTAINER_NAME" curl -sf "http://127.0.0.1:18006/status" >/dev/null 2>&1; then
    echo "✅ 容器已就绪"
    break
  fi
  if [[ $i -eq 30 ]]; then
    echo "❌ 容器启动超时"
    docker logs "$CONTAINER_NAME"
    exit 1
  fi
  echo "  ⏳ 等待中... ($i/30)"
  sleep 1
done

# 5. 健康检查
echo ""
echo "🏥 Step 4: 健康检查..."
STATUS=$(docker exec "$CONTAINER_NAME" curl -s "http://127.0.0.1:18006/status" || echo '{}')
echo "Status: $STATUS"

# 6. 容器日志
echo ""
echo "📋 Step 5: 容器日志（最后 10 行）..."
docker logs "$CONTAINER_NAME" 2>&1 | tail -10

echo ""
echo "✅ 验证完成！"
echo ""
echo "容器信息："
docker ps --filter "name=$CONTAINER_NAME" --format "table {{.Names}}\t{{.Ports}}\t{{.Status}}"

echo ""
echo "🧪 测试命令示例："
echo "  # 查看状态"
echo "  curl http://127.0.0.1:${PORT}/status"
echo ""
echo "  # 查看日志"
echo "  docker logs -f $CONTAINER_NAME"
echo ""
echo "  # 进入容器"
echo "  docker exec -it $CONTAINER_NAME /bin/bash"
echo ""
echo "✋ 容器将在脚本退出时自动清理。按 Ctrl+C 停止。"
echo ""

# 保持容器运行直到用户中断
wait
