#!/usr/bin/env bash
set -euo pipefail

HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$(cd "${HOOK_DIR}/../.." && pwd)"
ENV_PATH="${MNEMON_SKILL_LOOP_ENV:-${CONFIG_DIR}/mnemon-skill/env.sh}"
if [[ -f "${ENV_PATH}" ]]; then
  # shellcheck source=/dev/null
  source "${ENV_PATH}"
fi

SKILL_LOOP_DIR="${MNEMON_SKILL_LOOP_DIR:-${CONFIG_DIR}/mnemon-skill}"
ACTIVE_DIR="${MNEMON_SKILL_LOOP_ACTIVE_DIR:-${SKILL_LOOP_DIR}/skills/active}"
STALE_DIR="${MNEMON_SKILL_LOOP_STALE_DIR:-${SKILL_LOOP_DIR}/skills/stale}"
ARCHIVED_DIR="${MNEMON_SKILL_LOOP_ARCHIVED_DIR:-${SKILL_LOOP_DIR}/skills/archived}"
HOST_SKILLS_DIR="${MNEMON_SKILL_LOOP_HOST_SKILLS_DIR:-${CONFIG_DIR}/skills}"
GUIDE_FILE="${SKILL_LOOP_DIR}/GUIDE.md"

mkdir -p "${ACTIVE_DIR}" "${STALE_DIR}" "${ARCHIVED_DIR}" "${HOST_SKILLS_DIR}"

is_generated_skill() {
  [[ -f "$1/.mnemon-skill-generated" ]]
}

is_active_skill_id() {
  local skill_id="$1"
  [[ -d "${ACTIVE_DIR}/${skill_id}" && -f "${ACTIVE_DIR}/${skill_id}/SKILL.md" ]]
}

REMOVED=0
SYNCED=0
SKIPPED=0

while IFS= read -r marker; do
  skill_dir="$(dirname "${marker}")"
  skill_id="$(basename "${skill_dir}")"
  if ! is_active_skill_id "${skill_id}"; then
    rm -rf "${skill_dir}"
    REMOVED=$((REMOVED + 1))
  fi
done < <(find "${HOST_SKILLS_DIR}" -mindepth 2 -maxdepth 2 -name .mnemon-skill-generated -print 2>/dev/null)

while IFS= read -r src_dir; do
  skill_id="$(basename "${src_dir}")"
  dst_dir="${HOST_SKILLS_DIR}/${skill_id}"

  if [[ ! -f "${src_dir}/SKILL.md" ]]; then
    continue
  fi

  if [[ -e "${dst_dir}" ]]; then
    if ! is_generated_skill "${dst_dir}"; then
      echo "[mnemon-skill] Skip active skill '${skill_id}': host skill already exists and is not generated by Mnemon."
      SKIPPED=$((SKIPPED + 1))
      continue
    fi
  fi

  rm -rf "${dst_dir}"
  cp -R "${src_dir}" "${dst_dir}"
  touch "${dst_dir}/.mnemon-skill-generated"
  SYNCED=$((SYNCED + 1))
done < <(find "${ACTIVE_DIR}" -mindepth 1 -maxdepth 1 -type d -print 2>/dev/null | sort)

echo "[mnemon-skill] Prime"
echo
echo "MNEMON_SKILL_LOOP_ENV=${ENV_PATH}"
echo "MNEMON_SKILL_LOOP_DIR=${SKILL_LOOP_DIR}"
echo "Canonical active: ${ACTIVE_DIR}"
echo "Canonical stale: ${STALE_DIR}"
echo "Canonical archived: ${ARCHIVED_DIR}"
echo "Host skill surface: ${HOST_SKILLS_DIR}"
echo "Prime sync: ${SYNCED} active skill(s) synced, ${REMOVED} generated view(s) removed, ${SKIPPED} conflict(s) skipped."
echo
echo "Use host-native skill discovery. Do not inject all skill bodies into the prompt."
echo

if [[ -f "${GUIDE_FILE}" ]]; then
  echo "----- SKILL GUIDE -----"
  cat "${GUIDE_FILE}"
fi
