#!/bin/bash
set -e

LOG_FILE="$PWD/download-github.log"
exec > >(tee -a "$LOG_FILE") 2>&1

log_info()  { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [INFO]  $*"; }
log_warn()  { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [WARN]  $*"; }
log_error() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] [ERROR] $*" >&2; }

WORK_DIR="$PWD"
CACHE_DIR="$WORK_DIR/deps-cache"
mkdir -p "$CACHE_DIR"

REPOS=(
  "https://github.com/nodejs/node.git"
  "https://github.com/emqx/emqx.git"
  "https://github.com/redis/redis.git"
  "https://github.com/MariaDB/server.git"
  "https://github.com/LuaJIT/LuaJIT.git"
  "https://github.com/tinygo-org/tinygo.git"
  "https://github.com/taosdata/TDengine.git"
)

TAGS=(
  "v18.20.3"
  "v5.8.2"
  "7.2.5"
  "mariadb-10.11.8"
  "v2.1.0-beta3"
  "v0.32.0"
  "ver-3.3.8.11"
)

NAMES=(
  "node"
  "emqx"
  "redis"
  "mariadb"
  "luajit"
  "tinygo"
  "td"
)

log_info "🚀 开始检查并按需下载 GitHub 仓库（带进度）"

for i in "${!NAMES[@]}"; do
  name="${NAMES[$i]}"
  repo_url="${REPOS[$i]}"
  expected_tag="${TAGS[$i]}"
  local_path="$CACHE_DIR/$name"

  log_info "🔍 检查 [$name] (期望 tag: $expected_tag)"

  if [[ ! -d "$local_path/.git" ]]; then
    log_info "⬇️  [$name] 未下载，开始克隆..."
    if git clone --progress --branch "$expected_tag" --depth=1 "$repo_url" "$local_path" 2>&1; then
      log_info "✅ [$name] 克隆完成"
    else
      log_warn "⚠️  [$name] 直接克隆失败，尝试通用方式..."
      git clone --progress --depth=1 "$repo_url" "$local_path" 2>&1
      git -C "$local_path" fetch --tags --progress 2>&1
      git -C "$local_path" fetch origin '+refs/tags/*:refs/tags/*' 2>/dev/null || true
      git -C "$local_path" checkout "$expected_tag" 2>&1
      log_info "✅ [$name] 通过回退方式完成"
    fi
    continue
  fi

  # 确保 tag 可解析
  if ! git -C "$local_path" rev-parse --verify "$expected_tag" >/dev/null 2>&1; then
    log_info "🔄 [$name] 目标 tag 不存在，正在拉取 tags..."
    git -C "$local_path" fetch --tags --progress 2>&1
    git -C "$local_path" fetch origin '+refs/tags/*:refs/tags/*' 2>/dev/null || true
  fi

  # === 精准 commit 比较（修复重复 checkout 的关键）===
  if target_commit=$(git -C "$local_path" rev-parse "$expected_tag^{commit}" 2>/dev/null); then
    : # 成功解析 annotated tag
  else
    target_commit=$(git -C "$local_path" rev-parse "$expected_tag")
  fi
  current_commit=$(git -C "$local_path" rev-parse HEAD)

  # 统一转小写（防御大小写问题，虽然罕见）
  target_commit="${target_commit,,}"
  current_commit="${current_commit,,}"

  if [[ "$current_commit" == "$target_commit" ]]; then
    log_info "✅ [$name] 已存在且版本正确（commit 匹配）"
  else
    log_info "🔄 [$name] 当前 commit 不匹配，切换到 $expected_tag..."
    git -C "$local_path" checkout -f "$expected_tag" 2>&1
    log_info "✅ [$name] 切换完成"
  fi
done

log_info "🎉 所有仓库已就绪！"
echo "🎯 下一步：可运行 build.sh 或提取头文件"
