#!/bin/bash
source ./.vala_skillhub_config
HASH_FILE=./.vala_skill_hashes
touch "${HASH_FILE}"

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}')
}

synced_count=0
skipped_count=0
synced_skills=()

for skill_dir in ./skills/*/; do
  skill_name=$(basename "${skill_dir}")
  if [ "${skill_name}" = "use_vala_skillhub.vala" ]; 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
    echo "[skip] ${skill_name} — 无变更"
    skipped_count=$((skipped_count + 1))
    continue
  fi
  echo "[sync] ${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=$(cat "${skill_dir}/skill.json" | grep '"description"' | 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}'
  fi
  rm -rf ./tmp/skill_push/${repo_name}
  mkdir -p ./tmp/skill_push/${repo_name}
  cp -r ${skill_dir}* ./tmp/skill_push/${repo_name}/
  cp -r ${skill_dir}.[!.]* ./tmp/skill_push/${repo_name}/ 2>/dev/null || true
  cd ./tmp/skill_push/${repo_name}
  git init >/dev/null 2>&1
  git checkout -b main >/dev/null 2>&1
  git config user.name "OpenClaw Bot" >/dev/null 2>&1
  git config user.email "bot@openclaw.ai" >/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 2>&1
  rm -rf ./tmp/skill_push/${repo_name}
  grep -v "^${skill_name} " "${HASH_FILE}" > "${HASH_FILE}.tmp" || true
  echo "${skill_name} ${current_hash}" >> "${HASH_FILE}.tmp"
  mv "${HASH_FILE}.tmp" "${HASH_FILE}"
  echo "[done] ${skill_name} — 推送完成"
  synced_count=$((synced_count + 1))
  synced_skills+=("${skill_name}")
done

echo "=== 同步完成 ==="
echo "推送技能数量: ${synced_count}"
if [ ${synced_count} -gt 0 ]; then
  echo "推送的技能: ${synced_skills[*]}"
fi
echo "跳过技能数量: ${skipped_count}"
