#!/bin/bash
# =============================================================================
# WOOO TECH - MOMO Pro System
# 簡化版建置與部署腳本
# 用途: 本地建置 Docker 映像並部署到 K3s (不依賴 Harbor)
# =============================================================================

set -e

# 顏色定義
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 配置
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
IMAGE_NAME="momo-pro-system"
IMAGE_TAG="${1:-local}"
K3S_HOST="${K3S_HOST:-192.168.0.110}"
K3S_USER="${K3S_USER:-wooo}"

# Telegram 通知
TELEGRAM_BOT_TOKEN="<TELEGRAM_BOT_TOKEN>"
TELEGRAM_CHAT_ID="5619078117"

send_telegram() {
    local message="$1"
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d chat_id="${TELEGRAM_CHAT_ID}" \
        -d parse_mode="HTML" \
        -d text="$message" > /dev/null 2>&1 || true
}

log() {
    echo -e "${GREEN}[$(date '+%H:%M:%S')]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date '+%H:%M:%S')] ⚠️ $1${NC}"
}

error() {
    echo -e "${RED}[$(date '+%H:%M:%S')] ❌ $1${NC}"
    send_telegram "❌ <b>部署失敗</b>%0A%0A錯誤: $1%0A時間: $(date '+%Y-%m-%d %H:%M:%S')"
    exit 1
}

# 檢查必要工具
check_requirements() {
    log "檢查必要工具..."

    if ! command -v docker &> /dev/null; then
        error "Docker 未安裝"
    fi

    if ! command -v ssh &> /dev/null; then
        error "SSH 未安裝"
    fi

    log "✅ 工具檢查通過"
}

# 建置 Docker 映像
build_image() {
    log "🔨 開始建置 Docker 映像..."
    cd "$PROJECT_ROOT"

    docker build -t "${IMAGE_NAME}:${IMAGE_TAG}" . || error "Docker 建置失敗"

    log "✅ Docker 映像建置完成: ${IMAGE_NAME}:${IMAGE_TAG}"
}

# 匯出映像到 K3s
export_to_k3s() {
    log "📤 匯出映像到 K3s..."

    # 儲存映像為 tar
    local tmp_file="/tmp/${IMAGE_NAME}-${IMAGE_TAG}.tar"
    docker save "${IMAGE_NAME}:${IMAGE_TAG}" -o "$tmp_file" || error "映像匯出失敗"

    log "📦 映像大小: $(du -h "$tmp_file" | cut -f1)"

    # 傳輸到 K3s 主機
    log "🚀 傳輸到 K3s 主機 (${K3S_HOST})..."
    scp "$tmp_file" "${K3S_USER}@${K3S_HOST}:/tmp/" || error "SCP 傳輸失敗"

    # 匯入到 K3s containerd
    log "📥 匯入到 K3s containerd..."
    ssh "${K3S_USER}@${K3S_HOST}" "sudo k3s ctr images import /tmp/${IMAGE_NAME}-${IMAGE_TAG}.tar" || error "K3s 匯入失敗"

    # 清理暫存檔
    rm -f "$tmp_file"
    ssh "${K3S_USER}@${K3S_HOST}" "rm -f /tmp/${IMAGE_NAME}-${IMAGE_TAG}.tar"

    log "✅ 映像已匯入 K3s"
}

# 重啟 K8s Deployment
restart_deployment() {
    log "🔄 重啟 K8s Deployment..."

    ssh "${K3S_USER}@${K3S_HOST}" "sudo kubectl rollout restart deployment/momo-app deployment/momo-scheduler -n momo" || error "重啟失敗"

    log "⏳ 等待 Deployment 就緒..."
    ssh "${K3S_USER}@${K3S_HOST}" "sudo kubectl rollout status deployment/momo-app -n momo --timeout=120s" || error "momo-app 啟動失敗"
    ssh "${K3S_USER}@${K3S_HOST}" "sudo kubectl rollout status deployment/momo-scheduler -n momo --timeout=120s" || error "momo-scheduler 啟動失敗"

    log "✅ Deployment 重啟完成"
}

# 健康檢查
health_check() {
    log "🏥 執行健康檢查..."

    local retries=5
    local wait=10

    for i in $(seq 1 $retries); do
        if curl -s "https://mo.wooo.work/health" | grep -q "healthy"; then
            log "✅ 健康檢查通過"
            return 0
        fi
        warn "健康檢查失敗，等待 ${wait} 秒後重試 ($i/$retries)..."
        sleep $wait
    done

    error "健康檢查失敗"
}

# 推送到 Docker Hub (可選)
push_to_dockerhub() {
    local dockerhub_user="${DOCKERHUB_USER:-woootech}"
    local full_image="${dockerhub_user}/${IMAGE_NAME}:${IMAGE_TAG}"

    log "☁️ 推送到 Docker Hub: ${full_image}..."

    docker tag "${IMAGE_NAME}:${IMAGE_TAG}" "${full_image}"
    docker push "${full_image}" || {
        warn "Docker Hub 推送失敗（需要 docker login）"
        return 1
    }

    log "✅ 已推送到 Docker Hub"
}

# 主流程
main() {
    local start_time=$(date +%s)

    echo ""
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  MOMO Pro System - 建置與部署${NC}"
    echo -e "${BLUE}========================================${NC}"
    echo ""

    check_requirements
    build_image
    export_to_k3s
    restart_deployment
    health_check

    # 可選: 推送到 Docker Hub
    if [[ "${PUSH_TO_DOCKERHUB}" == "true" ]]; then
        push_to_dockerhub
    fi

    local end_time=$(date +%s)
    local duration=$((end_time - start_time))

    echo ""
    echo -e "${GREEN}========================================${NC}"
    echo -e "${GREEN}  ✅ 部署完成！${NC}"
    echo -e "${GREEN}  耗時: ${duration} 秒${NC}"
    echo -e "${GREEN}========================================${NC}"

    send_telegram "✅ <b>MOMO Pro 部署成功</b>%0A%0A🏷️ 版本: ${IMAGE_TAG}%0A⏱️ 耗時: ${duration} 秒%0A🌐 https://mo.wooo.work"
}

# 執行
main "$@"
