#!/usr/bin/env bash
# Helper for per-repo skill deployment via direnv
# Source this from your .envrc or copy the functions
#
# Usage in .envrc:
#   source ~/proj/skills/bin/use-skills.sh
#   export CODEX_HOME="$PWD/.codex"   # Optional: per-repo Codex skills
#   use_skills worklog web-search
#
# Or with manifest file:
#   source ~/proj/skills/bin/use-skills.sh
#   load_skills_from_manifest

set -euo pipefail

# Default repo - uses local git, override with SKILLS_REPO for remote
SKILLS_REPO="${SKILLS_REPO:-git+file://$HOME/proj/skills}"

# Install a single skill via nix build + symlink
use_skill() {
  local skill="$1"
  local out

  out=$(nix build --print-out-paths --no-link "${SKILLS_REPO}#${skill}") || {
    echo "use_skill: failed to build ${skill}" >&2
    return 1
  }

  mkdir -p .claude/skills .opencode/skills
  ln -sfn "$out" ".claude/skills/${skill}"
  ln -sfn "$out" ".opencode/skills/${skill}"
  if [[ -n "${CODEX_HOME:-}" ]]; then
    mkdir -p "${CODEX_HOME}/skills"
    ln -sfn "$out" "${CODEX_HOME}/skills/${skill}"
  fi
  echo "use_skill: ${skill}"
}

# Install multiple skills
use_skills() {
  for skill in "$@"; do
    use_skill "$skill" || return 1
  done
}

# Load skills from .skills manifest file
load_skills_from_manifest() {
  [[ ! -f .skills ]] && return 0
  while IFS= read -r skill || [[ -n "$skill" ]]; do
    # Skip empty lines and comments
    [[ -z "$skill" || "$skill" =~ ^[[:space:]]*# ]] && continue
    # Strip inline comments and whitespace
    skill="${skill%%#*}"
    skill="${skill// /}"
    [[ -n "$skill" ]] && { use_skill "$skill" || return 1; }
  done < .skills
}
