#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"

cd "$SCRIPT_DIR"

# 检查 .env
if [ ! -f .env ]; then
    echo "❌ 未找到 .env，请先执行：cp .env.example .env && vim .env"
    exit 1
fi

CMD="${1:-help}"
BRANCH="${2:-master}"

case "$CMD" in

    start)
        IMAGE_NAME="$(grep APP_NAME .env | cut -d= -f2 | tr -d '"' | tr -d "'" | xargs)-frontend:latest"
        IMAGE_NAME="${IMAGE_NAME:-ghb-frontend:latest}"
        if ! docker image inspect "$IMAGE_NAME" > /dev/null 2>&1; then
            echo "❌ 镜像 $IMAGE_NAME 不存在，请先执行: bash deploy.sh build"
            exit 1
        fi
        echo ">>> 停掉旧容器..."
        docker compose -f "$COMPOSE_FILE" down 2>/dev/null || true
        echo ""
        echo ">>> 启动..."
        docker compose -f "$COMPOSE_FILE" up -d --force-recreate
        echo ""
        echo "✅ 已启动"
        echo "   地址: http://localhost:$(grep FRONTEND_PORT .env | cut -d= -f2 | tr -d '"' | tr -d "'" | xargs)"
        echo "   日志: bash deploy.sh logs"
        ;;

    build)
        echo ">>> 宿主机构建 dist..."
        cd "$PROJECT_DIR"

        if ! command -v pnpm &> /dev/null; then
            echo "安装 pnpm..."
            npm install -g pnpm
        fi

        pnpm install
        pnpm build

        echo ""
        echo ">>> 编译 Docker 镜像..."
        cd "$SCRIPT_DIR"
        docker compose -f "$COMPOSE_FILE" build frontend
        echo ""
        echo "✅ 编译完成，执行 bash deploy.sh start 启动"
        ;;

    rebuild)
        echo ">>> 切到分支 ${BRANCH} 并拉取最新代码..."
        cd "$PROJECT_DIR"
        git fetch origin
        git checkout "${BRANCH}"
        git pull origin "${BRANCH}"

        echo ""
        echo ">>> 宿主机构建 dist..."
        if ! command -v pnpm &> /dev/null; then
            echo "安装 pnpm..."
            npm install -g pnpm
        fi

        pnpm install
        pnpm build

        echo ""
        echo ">>> 重新编译 + 启动..."
        cd "$SCRIPT_DIR"
        docker compose -f "$COMPOSE_FILE" down 2>/dev/null || true
        docker compose -f "$COMPOSE_FILE" build frontend
        docker compose -f "$COMPOSE_FILE" up -d --force-recreate
        echo ""
        echo "✅ 重新部署完成（分支: ${BRANCH}）"
        echo "   前端地址: http://localhost:$(grep FRONTEND_PORT .env | cut -d= -f2 | tr -d '"' | tr -d "'" | xargs)"
        ;;

    stop)
        docker compose -f "$COMPOSE_FILE" down 2>/dev/null || true
        echo "✅ 已停止"
        ;;

    logs)
        docker compose -f "$COMPOSE_FILE" logs -f --tail=200
        ;;

    status)
        docker compose -f "$COMPOSE_FILE" ps -a
        ;;

    *)
        echo "用法: bash deploy.sh <命令> [分支]"
        echo ""
        echo "  start             停旧容器 → 启动（日常使用，不重新编译）"
        echo "  build             编译 dist + 编译镜像（代码变更后用一次）"
        echo "  rebuild [分支]     拉取分支代码 + 编译 + 启动（一步到位）"
        echo "  stop              停止"
        echo "  logs              查看日志"
        echo "  status            查看容器状态"
        echo ""
        echo "分支参数默认 master，示例："
        echo "  bash deploy.sh rebuild test"
        echo ""
        echo "首次部署：cp .env.example .env && vim .env && bash deploy.sh rebuild"
        echo "日常更新：bash deploy.sh start"
        echo "代码变更：bash deploy.sh rebuild <分支>"
        ;;
esac
