#!/usr/bin/env bash
# install-claude-skills.sh — symlink each skill from a Claude-Skills repo into
# ~/.claude/skills/.
#
# Originally lived at <Claude-Skills>/scripts/install.sh where the repo root
# could be inferred from $SCRIPT_DIR/..  After being migrated into the Scripts
# monorepo (sh/install-claude-skills/), that inference is no longer valid, so
# the target repo MUST be provided explicitly via:
#
#     --skills-repo PATH      (CLI flag, takes precedence)
#     CLAUDE_SKILLS_REPO      (environment variable, fallback)
#
# Idempotent: re-running after a git pull is safe. Existing symlinks are
# refreshed; non-symlink entries with the same name are left untouched and
# reported (you decide whether to replace them).
#
# Usage:
#   bash install-claude-skills.sh --skills-repo ~/Github/Claude-Skills
#   CLAUDE_SKILLS_REPO=~/Github/Claude-Skills bash install-claude-skills.sh
#   bash install-claude-skills.sh --skills-repo PATH seo-blog-write-platform [...]
#
# A skill is any top-level directory under the repo that contains a SKILL.md.

set -euo pipefail

# --- Parse args -------------------------------------------------------------
SKILLS_REPO="${CLAUDE_SKILLS_REPO:-}"
REQUESTED=()

while (( $# > 0 )); do
  case "$1" in
    --skills-repo)
      [[ $# -ge 2 ]] || { echo "[install] --skills-repo requires a PATH argument" >&2; exit 2; }
      SKILLS_REPO="$2"
      shift 2
      ;;
    --skills-repo=*)
      SKILLS_REPO="${1#--skills-repo=}"
      shift
      ;;
    -h|--help)
      sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//'
      exit 0
      ;;
    --) shift; REQUESTED+=("$@"); break ;;
    -*)
      echo "[install] unknown flag: $1" >&2
      exit 2
      ;;
    *)
      REQUESTED+=("$1")
      shift
      ;;
  esac
done

if [[ -z "$SKILLS_REPO" ]]; then
  echo "[install] missing skills repo. Pass --skills-repo PATH or set CLAUDE_SKILLS_REPO." >&2
  exit 2
fi

if [[ ! -d "$SKILLS_REPO" ]]; then
  echo "[install] skills repo does not exist or is not a directory: $SKILLS_REPO" >&2
  exit 2
fi

REPO_ROOT="$(cd "$SKILLS_REPO" && pwd)"
TARGET_DIR="${HOME}/.claude/skills"

mkdir -p "$TARGET_DIR"

# --- Discover skills (any top-level dir containing SKILL.md) ----------------
discover_skills() {
  find "$REPO_ROOT" -mindepth 2 -maxdepth 2 -name "SKILL.md" -type f \
    -exec dirname {} \; | sort -u
}

# --- Filter against optional CLI args ---------------------------------------
filter_skills() {
  local all=("$@")
  if [ "${#REQUESTED[@]}" -eq 0 ]; then
    printf '%s\n' "${all[@]}"
    return
  fi
  for s in "${all[@]}"; do
    name="$(basename "$s")"
    for r in "${REQUESTED[@]}"; do
      [ "$name" = "$r" ] && printf '%s\n' "$s"
    done
  done
}

# Portable replacement for `mapfile -t` (not in macOS bash 3.2).
ALL_SKILLS=()
while IFS= read -r line; do
  ALL_SKILLS+=("$line")
done < <(discover_skills)

if [ "${#ALL_SKILLS[@]}" -eq 0 ]; then
  echo "[install] no skills found under $REPO_ROOT (looking for */SKILL.md)" >&2
  exit 1
fi

SKILLS=()
while IFS= read -r line; do
  SKILLS+=("$line")
done < <(filter_skills "${ALL_SKILLS[@]}")

if [ "${#SKILLS[@]}" -eq 0 ]; then
  echo "[install] no skills matched the requested names: ${REQUESTED[*]}" >&2
  exit 1
fi

# --- Symlink each ---------------------------------------------------------
installed=0
skipped=0
for skill_dir in "${SKILLS[@]}"; do
  name="$(basename "$skill_dir")"
  link="$TARGET_DIR/$name"

  if [ -L "$link" ]; then
    # Existing symlink — refresh it to the current repo path.
    ln -sfn "$skill_dir" "$link"
    echo "[install] refreshed   $name → $skill_dir"
    installed=$((installed + 1))
  elif [ -e "$link" ]; then
    # Non-symlink entry with the same name — do not overwrite.
    echo "[install] SKIP        $name (existing non-symlink at $link — remove it first)" >&2
    skipped=$((skipped + 1))
  else
    ln -s "$skill_dir" "$link"
    echo "[install] linked      $name → $skill_dir"
    installed=$((installed + 1))
  fi
done

echo "[install] done — ${installed} installed/refreshed, ${skipped} skipped"
