#!/usr/bin/env bash
# postinstall.sh — runs after npm/bun install
# Installs bundled skills and any missing system dependencies.
# Never exits non-zero — failures print warnings but don't block install.

set -u

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# ─── 1. Install skills to ~/.claude/skills/ ──────────────────────────────────

SKILLS_SRC="$ROOT_DIR/skills"
SKILLS_DST="$HOME/.claude/skills"

if [ -d "$SKILLS_SRC" ]; then
  mkdir -p "$SKILLS_DST"
  for skill_dir in "$SKILLS_SRC"/*/; do
    skill_name="$(basename "$skill_dir")"
    if [ -f "$skill_dir/SKILL.md" ]; then
      mkdir -p "$SKILLS_DST/$skill_name"
      cp "$skill_dir/SKILL.md" "$SKILLS_DST/$skill_name/SKILL.md" 2>/dev/null && \
        echo "✓ Installed skill: $skill_name" || \
        echo "⚠  Could not install skill: $skill_name"
    fi
  done
fi

# ─── 2. Install missing system dependencies ──────────────────────────────────

install_with_brew() {
  local pkg="$1"
  local name="$2"
  local hint="$3"

  if command -v "$pkg" >/dev/null 2>&1; then
    return 0
  fi

  echo "$name not found. Attempting to install..."

  if command -v brew >/dev/null 2>&1; then
    if brew install "$pkg" 2>/dev/null; then
      echo "✓ Installed $name via Homebrew"
      return 0
    fi
  fi

  echo "⚠  Could not install $name automatically. $hint"
}

install_with_npm_global() {
  local cmd="$1"
  local pkg="$2"
  local name="$3"
  local hint="$4"

  if command -v "$cmd" >/dev/null 2>&1; then
    return 0
  fi

  echo "$name not found. Attempting to install..."

  if npm install -g "$pkg" 2>/dev/null; then
    echo "✓ Installed $name via npm"
    return 0
  fi

  echo "⚠  Could not install $name automatically. $hint"
}

# tmux is now bundled via @octomux/tmux-<platform>-<arch> optional dependencies.
# No system-level tmux install is needed.

# git
install_with_brew "git" "git" "Install with: brew install git"

# Claude Code CLI
install_with_npm_global "claude" "@anthropic-ai/claude-code" "Claude Code CLI" \
  "See: https://docs.anthropic.com/en/docs/claude-code"
