#!/bin/sh
# Installs the BulkImagen agent skill for your coding agent.
#
#   sh install.sh              detect the agent from the current directory
#   sh install.sh claude       ~/.claude/skills/bulkimagen/   (Claude Code)
#   sh install.sh cursor       .cursor/rules/bulkimagen.mdc   (Cursor)
#   sh install.sh agents       ./AGENTS.md                    (Codex, Copilot,
#                                                              Gemini CLI, Aider,
#                                                              Windsurf, Zed)
#
# Everything this script does: create a directory and download files into it.
# Nothing is executed, no config is rewritten, nothing runs in the background.
# Read it before piping it to a shell — including this one.
set -e

BASE="https://bulkimagen.com/skill"
TARGET="$1"

say() { printf '%s\n' "$*"; }

detect() {
  if [ -d ".cursor" ]; then say "cursor"; return; fi
  if [ -f "AGENTS.md" ]; then say "agents"; return; fi
  if [ -d ".claude" ] || [ -d "$HOME/.claude" ]; then say "claude"; return; fi
  say ""
}

if [ -z "$TARGET" ]; then
  TARGET="$(detect)"
  if [ -z "$TARGET" ]; then
    say "Could not tell which agent you use. Re-run with one of:"
    say "  sh install.sh claude    # Claude Code"
    say "  sh install.sh cursor    # Cursor"
    say "  sh install.sh agents    # Codex, Copilot, Gemini CLI, Aider, Windsurf, Zed"
    exit 1
  fi
  say "Detected: $TARGET"
fi

case "$TARGET" in
  claude)
    DEST="${2:-$HOME/.claude/skills/bulkimagen}"
    mkdir -p "$DEST/references" "$DEST/scripts"
    curl -fsSL "$BASE/SKILL.md"                       -o "$DEST/SKILL.md"
    curl -fsSL "$BASE/references/api.md"              -o "$DEST/references/api.md"
    curl -fsSL "$BASE/references/choosing-a-model.md" -o "$DEST/references/choosing-a-model.md"
    curl -fsSL "$BASE/scripts/bulkimagen.mjs"         -o "$DEST/scripts/bulkimagen.mjs"
    chmod +x "$DEST/scripts/bulkimagen.mjs"
    say "Installed the BulkImagen skill to $DEST"
    ;;

  cursor)
    DEST="${2:-.cursor/rules}"
    mkdir -p "$DEST"
    curl -fsSL "$BASE/bulkimagen.mdc" -o "$DEST/bulkimagen.mdc"
    say "Installed the BulkImagen rule to $DEST/bulkimagen.mdc"
    ;;

  agents)
    DEST="${2:-AGENTS.md}"
    if [ -f "$DEST" ] && grep -q "BulkImagen — bulk AI image generation" "$DEST"; then
      say "$DEST already contains the BulkImagen section — nothing to do."
      exit 0
    fi
    # Appends; never rewrites what is already in the file.
    TMP="$(mktemp)"
    curl -fsSL "$BASE/AGENTS.md" -o "$TMP"
    if [ -f "$DEST" ]; then printf '\n' >> "$DEST"; fi
    cat "$TMP" >> "$DEST"
    rm -f "$TMP"
    say "Appended the BulkImagen section to $DEST"
    ;;

  *)
    say "Unknown target: $TARGET (expected claude, cursor or agents)"
    exit 1
    ;;
esac

say ""
say "Next: create a key at https://bulkimagen.com/dashboard/api-keys (paid plans), then"
say "  export BULKIMAGEN_API_KEY=bik_live_..."
