#!/bin/bash
# =============================================================================
# 企微IT智能服务台 — 一键构建 & 部署脚本（共享域名版）
# =============================================================================
# 说明：与 IT 数据查询平台共享域名 it-dataquery.dc.servyou-it.com
#   路由：
#     /           → IT 数据查询平台
#     /itdesk/    → H5 员工咨询端
#     /itagent/   → 坐席工作台
#     /api/       → 后端 FastAPI
#
# 用法：
#   bash scripts/deploy.sh          # 完整构建 + 启动
#   bash scripts/deploy.sh --build  # 仅构建前端 + 后端镜像
#   bash scripts/deploy.sh --up     # 仅启动（已构建过）
#   bash scripts/deploy.sh --down   # 停止所有服务
#   bash scripts/deploy.sh --status  # 查看服务状态
#   bash scripts/deploy.sh --pack   # 打包部署文件（用于 SCP 到远程服务器）
# =============================================================================

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

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'  # No Color

info()  { echo -e "${BLUE}[INFO]${NC}  $1"; }
ok()    { echo -e "${GREEN}[OK]${NC}    $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# 项目根目录（脚本所在目录的上级）
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$PROJECT_ROOT"

# 部署包名（含日期）
DEPLOY_PKG="it-smart-desk-$(date +%Y%m%d%H%M).tar.gz"

# --------------------------------------------------------------------------
# 前置检查
# --------------------------------------------------------------------------
check_prerequisites() {
    info "检查前置条件..."

    # 检查 Docker
    if ! command -v docker &> /dev/null; then
        error "Docker 未安装，请先安装 Docker"
    fi
    ok "Docker 已安装"

    # 检查 Docker Compose
    if ! docker compose version &> /dev/null; then
        error "Docker Compose 未安装或版本过低"
    fi
    ok "Docker Compose 可用"

    # 检查 .env 文件
    if [ ! -f .env ]; then
        warn ".env 文件不存在，从模板创建..."
        if [ -f .env.production ]; then
            cp .env.production .env
            warn "已创建 .env，请编辑填入真实配置后再部署"
            warn "关键配置：WECOM_CORP_ID, WECOM_SECRET, WECOM_TOKEN, WECOM_ENCODING_AES_KEY"
            exit 1
        else
            error ".env.production 模板不存在"
        fi
    fi
    ok ".env 配置文件就绪"
}

# --------------------------------------------------------------------------
# 创建外部网络（与数据平台互联）
# --------------------------------------------------------------------------
ensure_network() {
    info "检查外部网络 it-platform-net..."
    if docker network inspect it-platform-net &> /dev/null; then
        ok "外部网络 it-platform-net 已存在"
    else
        info "创建外部网络 it-platform-net..."
        docker network create it-platform-net
        ok "外部网络创建成功"
    fi
}

# --------------------------------------------------------------------------
# 构建前端
# --------------------------------------------------------------------------
build_frontends() {
    info "构建 H5 员工咨询端（/itdesk/）..."
    cd "$PROJECT_ROOT/frontend-h5"
    npm install --prefer-offline
    npm run build
    ok "H5 员工咨询端构建完成 (dist/ → /itdesk/)"

    info "构建坐席工作台（/itagent/）..."
    cd "$PROJECT_ROOT/frontend-agent"
    npm install --prefer-offline
    npm run build
    ok "坐席工作台构建完成 (dist/ → /itagent/)"

    cd "$PROJECT_ROOT"
}

# --------------------------------------------------------------------------
# 构建后端镜像
# --------------------------------------------------------------------------
build_backend() {
    info "构建后端 Docker 镜像..."
    docker compose build backend
    ok "后端镜像构建完成"
}

# --------------------------------------------------------------------------
# 启动服务
# --------------------------------------------------------------------------
start_services() {
    ensure_network
    info "启动所有服务..."
    docker compose up -d
    ok "所有服务已启动"

    echo ""
    info "等待服务就绪（约 30 秒，含数据库迁移）..."
    sleep 30

    # 健康检查
    if curl -sf http://localhost:18080/itdesk/health > /dev/null 2>&1; then
        ok "后端服务健康检查通过"
    else
        warn "后端健康检查未通过，请查看日志：docker compose logs backend"
    fi
}

# --------------------------------------------------------------------------
# 停止服务
# --------------------------------------------------------------------------
stop_services() {
    info "停止所有服务..."
    docker compose down
    ok "所有服务已停止（数据卷保留，不丢失数据）"
}

# --------------------------------------------------------------------------
# 查看状态
# --------------------------------------------------------------------------
show_status() {
    info "服务状态："
    docker compose ps
    echo ""
    info "资源占用："
    docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" \
        $(docker compose ps -q 2>/dev/null) 2>/dev/null || echo "服务未启动"
}

# --------------------------------------------------------------------------
# 打包部署文件（用于 SCP 到远程服务器）
# --------------------------------------------------------------------------
pack_deploy() {
    info "打包部署文件..."

    # 确保前端已构建
    if [ ! -d "$PROJECT_ROOT/frontend-h5/dist" ] || [ ! -d "$PROJECT_ROOT/frontend-agent/dist" ]; then
        warn "前端 dist 不存在，先构建..."
        build_frontends
    fi

    # 打包所需文件（排除 node_modules、.git、本地数据库等）
    tar czf "$PROJECT_ROOT/$DEPLOY_PKG" \
        --exclude='node_modules' \
        --exclude='.git' \
        --exclude='__pycache__' \
        --exclude='*.pyc' \
        --exclude='*.db' \
        --exclude='.env' \
        --exclude='*.tar.gz' \
        -C "$PROJECT_ROOT" \
        backend/ \
        frontend-h5/dist/ \
        frontend-agent/dist/ \
        nginx/ \
        docker-compose.yml \
        .env.production \
        scripts/ \
        docs/

    ok "部署包已创建：$DEPLOY_PKG"
    echo ""
    info "远程部署步骤："
    echo "  1. scp $DEPLOY_PKG user@server:/opt/it-smart-desk/"
    echo "  2. ssh user@server"
    echo "  3. cd /opt/it-smart-desk && tar xzf $DEPLOY_PKG"
    echo "  4. cp .env.production .env && vim .env  # 填入真实配置"
    echo "  5. bash scripts/deploy.sh"
}

# --------------------------------------------------------------------------
# 主流程
# --------------------------------------------------------------------------
main() {
    echo "========================================="
    echo "  企微IT智能服务台 — 部署工具"
    echo "  共享域名: it-dataquery.dc.servyou-it.com"
    echo "========================================="
    echo ""

    case "${1:-full}" in
        --build)
            check_prerequisites
            build_frontends
            build_backend
            ok "构建完成！运行 bash scripts/deploy.sh --up 启动服务"
            ;;
        --up)
            check_prerequisites
            start_services
            ;;
        --down)
            stop_services
            ;;
        --status)
            show_status
            ;;
        --pack)
            build_frontends
            pack_deploy
            ;;
        full|"")
            check_prerequisites
            build_frontends
            build_backend
            start_services
            echo ""
            echo "========================================="
            ok "部署完成！"
            echo "========================================="
            echo ""
            echo "  H5 员工端：http://it-dataquery.dc.servyou-it.com/itdesk/"
            echo "  坐席工作台：http://it-dataquery.dc.servyou-it.com/itagent/"
            echo "  API 文档：  http://it-dataquery.dc.servyou-it.com/api/docs"
            echo "  数据平台：  http://it-dataquery.dc.servyou-it.com/"
            echo ""
            echo "  本地测试：  http://localhost:18080/itdesk/"
            echo "  查看日志：docker compose logs -f"
            echo "  停止服务：bash scripts/deploy.sh --down"
            ;;
        *)
            echo "用法：bash scripts/deploy.sh [--build|--up|--down|--status|--pack]"
            exit 1
            ;;
    esac
}

main "$@"
