#!/usr/bin/env bash
# ==============================================================================
# BySimplicity — Skills Manager & Installer for Agentic Workflows
# Installs and syncs agent skills for the current project, future projects,
# or globally to ~/.agents/skills/
# ==============================================================================

set -e

SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/.agents/skills"
GLOBAL_DIR="$HOME/.agents/skills"

show_help() {
  echo "Usage: ./scripts/install_skills.sh [option] [target_path]"
  echo ""
  echo "Options:"
  echo "  --global           Install all skills globally to ~/.agents/skills (accessible by any project)"
  echo "  --project <path>   Install all skills into target project's .agents/skills folder"
  echo "  --list             List all installed skills with short description"
  echo "  --help             Show this help message"
  echo ""
  echo "Examples:"
  echo "  ./scripts/install_skills.sh --global"
  echo "  ./scripts/install_skills.sh --project /Users/macbookpro/Desktop/MonNouveauProjet"
}

list_skills() {
  echo "Available skills in BySimplicity library ($SOURCE_DIR):"
  echo "========================================================"
  for skill_dir in "$SOURCE_DIR"/*; do
    if [ -d "$skill_dir" ] && [ -f "$skill_dir/SKILL.md" ]; then
      name=$(basename "$skill_dir")
      # Extract description from frontmatter if possible
      desc=$(grep -m 1 "^description:" "$skill_dir/SKILL.md" | sed 's/^description: *//' | tr -d '"' | cut -c 1-85)
      printf "  %-26s %s...\n" "$name" "$desc"
    fi
  done
}

install_global() {
  echo "Installing all skills globally into $GLOBAL_DIR..."
  mkdir -p "$GLOBAL_DIR"
  cp -R "$SOURCE_DIR"/* "$GLOBAL_DIR"/
  echo "✅ Successfully installed $(ls -1 "$SOURCE_DIR" | wc -l | tr -d ' ') skills globally!"
  echo "All your future Antigravity & AI Agent projects can now discover these skills."
}

install_project() {
  local target="$1"
  if [ -z "$target" ]; then
    echo "❌ Error: Please specify the target project path."
    show_help
    exit 1
  fi

  local target_skills="$target/.agents/skills"
  echo "Installing all skills into $target_skills..."
  mkdir -p "$target_skills"
  cp -R "$SOURCE_DIR"/* "$target_skills"/
  echo "✅ Successfully installed $(ls -1 "$SOURCE_DIR" | wc -l | tr -d ' ') skills into $target!"
}

# Main routing
case "$1" in
  --global)
    install_global
    ;;
  --project)
    install_project "$2"
    ;;
  --list)
    list_skills
    ;;
  --help|"")
    show_help
    ;;
  *)
    echo "Unknown option: $1"
    show_help
    exit 1
    ;;
esac
