#!/bin/bash
set -e

SKILLS_DIR="/root/.openclaw/skills"
WORKSPACE_DIR="$HOME/.hermes/workspace"
cd "$WORKSPACE_DIR"

source ./.vala_skillhub_config

HASH_FILE=./.shared_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}')
}

pushed=0
skipped=0
pushed_names=""

# Only process directories (skill dirs, not top-level files)
for skill_dir in "${SKILLS_DIR}"/*/; do
  [ -d "${skill_dir}" ] || continue
  skill_name=$(basename "${skill_dir}")

  # Determine repo name: must end with .vala
  if [[ "${skill_name}" == *.vala ]]; then
    repo_name="${skill_name}"
  else
    repo_name="${skill_name}.vala"
  fi

  current_hash=$(compute_skill_hash "${skill_dir}")
  stored_hash=$(grep "^${skill_name} " "${HASH_FILE}" 2>/dev/null | awk '{print $2}')

  if [ "${current_hash}" = "${stored_hash}" ] && [ -n "${stored_hash}" ]; then
    echo "[skip] ${skill_name} — 无变更"
    skipped=$((skipped + 1))
    continue
  fi

  echo "[sync] ${skill_name} — 检测到变更，开始推送..."

  # Check if remote repo exists
  http_code=$(curl -s -o /dev/null -w "%{http_code}" \
    "${GITEA_URL}/api/v1/repos/${GITEA_OWNER}/${repo_name}" \
    -H "Authorization: token ${GITEA_TOKEN}")

  # Create repo if not exists
  if [ "${http_code}" = "404" ]; then
    echo "  → 仓库不存在，创建中..."
    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, \"auto_init\": false}" > /dev/null
    echo "  → 仓库已创建"
  fi

  # Copy to temp dir and push
  tmp_dir="/tmp/shared_skill_push/${repo_name}"
  rm -rf "${tmp_dir}"
  mkdir -p "${tmp_dir}"
  cp -r "${skill_dir}." "${tmp_dir}/" 2>/dev/null || true

  pushd "${tmp_dir}" > /dev/null
  git init -q
  git checkout -B main -q
  git add -A
  git commit -m "auto-sync: ${skill_name} $(date +%Y-%m-%d_%H:%M)" -q || true
  git remote add origin "https://oauth2:${GITEA_TOKEN}@${GITEA_URL#https://}/${GITEA_OWNER}/${repo_name}.git" 2>/dev/null || true
  git push -u origin main --force -q 2>&1 | tail -1
  popd > /dev/null

  # Cleanup
  rm -rf "${tmp_dir}"

  # Update hash
  grep -v "^${skill_name} " "${HASH_FILE}" > "${HASH_FILE}.tmp" 2>/dev/null || true
  echo "${skill_name} ${current_hash}" >> "${HASH_FILE}.tmp"
  mv "${HASH_FILE}.tmp" "${HASH_FILE}"

  echo "[done] ${skill_name} — 推送完成"
  pushed=$((pushed + 1))
  pushed_names="${pushed_names} ${skill_name}"
done

summary="[shared-sync] $(date +%Y-%m-%d_%H:%M) — 推送 ${pushed} 个 skill:${pushed_names} | 跳过 ${skipped} 个（无变更）"
echo "${summary}"

if [ "${pushed}" -gt 0 ]; then
  echo "RESULT:pushed=${pushed}"
else
  echo "RESULT:no_changes"
fi
