#!/bin/bash
# Vala SkillHub 自动推送脚本

# 加载配置
source "$(dirname "$0")/../.vala_skillhub_config"
HASH_FILE="$(dirname "$0")/../.vala_skill_hashes"
WORK_DIR="$(dirname "$0")/.."
TMP_DIR="${WORK_DIR}/tmp/skill_push"

# 检查配置是否完整
if [ -z "${GITEA_TOKEN}" ] || [ "${GITEA_TOKEN}" = "<请在此处填写你的Gitea API Token，需拥有仓库创建和推送权限>" ]; then
  echo "错误：GITEA_TOKEN 未配置，请先在 .vala_skillhub_config 中填写有效的Token"
  exit 1
fi

if [ -z "${SOURCE_NAME}" ]; then
  echo "错误：SOURCE_NAME 未配置"
  exit 1
fi

# 计算技能目录哈希
compute_skill_hash() {
  local skill_dir="$1"
  (cd "${skill_dir}" && find . -type f -not -path '*/\.*' | LC_ALL=C sort | while read f; do echo "FILE:$f"; cat "$f"; done | sha256sum | awk '{print $1}')
}

mkdir -p "${TMP_DIR}"
touch "${HASH_FILE}"

sync_count=0
skip_count=0

# 遍历所有技能目录
for skill_dir in "${WORK_DIR}/skills/"*/; do
  skill_name=$(basename "${skill_dir}")
  
  # 跳过自身
  if [ "${skill_name}" = "use_vala_skillhub.vala" ]; then
    continue
  fi
  
  if [ ! -d "${skill_dir}" ]; then
    continue
  fi
  
  current_hash=$(compute_skill_hash "${skill_dir}")
  stored_hash=$(grep "^${skill_name} " "${HASH_FILE}" | awk '{print $2}')
  
  if [ "${current_hash}" = "${stored_hash}" ]; then
    skip_count=$((skip_count + 1))
    continue
  fi
  
  sync_count=$((sync_count + 1))
  echo "同步技能: ${skill_name}"
  
  repo_name="${skill_name}.${SOURCE_NAME}"
  
  # 检查仓库是否存在
  http_code=$(curl -s -o /dev/null -w "%{http_code}" \
    "${GITEA_URL}/api/v1/repos/${GITEA_OWNER}/${repo_name}" \
    -H "Authorization: token ${GITEA_TOKEN}")
  
  # 不存在则创建
  if [ "${http_code}" = "404" ]; then
    desc=""
    if [ -f "${skill_dir}/skill.json" ]; then
      desc=$(grep '"description"' "${skill_dir}/skill.json" | head -1 | sed 's/.*"description"[[:space:]]*:[[:space:]]*"\(.*\)".*/\1/')
    fi
    curl -s -X POST "${GITEA_URL}/api/v1/orgs/${GITEA_OWNER}/repos" \
      -H "Authorization: token ${GITEA_TOKEN}" \
      -H "Content-Type: application/json" \
      -d '{"name": "'"${repo_name}"'", "private": false, "description": "'"${desc}"'", "auto_init": false}' > /dev/null
  fi
  
  # 复制到临时目录推送
  rm -rf "${TMP_DIR}/${repo_name}"
  mkdir -p "${TMP_DIR}/${repo_name}"
  cp -r "${skill_dir}"* "${TMP_DIR}/${repo_name}/"
  cp -r "${skill_dir}".[!.]* "${TMP_DIR}/${repo_name}/" 2>/dev/null || true
  
  cd "${TMP_DIR}/${repo_name}"
  git init > /dev/null 2>&1
  git checkout -b main > /dev/null 2>&1
  git add -A > /dev/null 2>&1
  git commit -m "auto-sync: ${skill_name} $(date +%Y-%m-%d_%H:%M)" > /dev/null 2>&1
  git remote add origin "https://oauth2:${GITEA_TOKEN}@${GITEA_URL#https://}/${GITEA_OWNER}/${repo_name}.git" > /dev/null 2>&1
  git push -u origin main --force > /dev/null 2>&1
  cd - > /dev/null
  
  # 更新哈希
  grep -v "^${skill_name} " "${HASH_FILE}" > "${HASH_FILE}.tmp" || true
  echo "${skill_name} ${current_hash}" >> "${HASH_FILE}.tmp"
  mv "${HASH_FILE}.tmp" "${HASH_FILE}"
done

rm -rf "${TMP_DIR}"

echo "同步完成：推送 ${sync_count} 个技能，跳过 ${skip_count} 个无变更技能"
