#!/usr/bin/env bash
# =============================================================================
# Claude Code Marketing Skills Installer
# =============================================================================
# Installs and updates 5 curated marketing skill repositories:
#   1. coreyhaines31/marketingskills   - 30+ CRO, SEO, copywriting skills
#   2. AgriciDaniel/claude-seo         - 13 sub-skills, 7 SEO subagents
#   3. zubair-trabzada/ai-marketing-claude - 15-skill AI Marketing Suite
#   4. anthropics/claude-code          - Official frontend-design skill
#   5. TheCraigHewitt/seomachine       - Full SEO content workspace
# =============================================================================

set -euo pipefail

# ── Colors ────────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
BLUE='\033[0;34m'; CYAN='\033[0;36m'; BOLD='\033[1m'; RESET='\033[0m'

# ── Helpers ───────────────────────────────────────────────────────────────────
info()    { echo -e "${CYAN}[INFO]${RESET}  $*"; }
success() { echo -e "${GREEN}[OK]${RESET}    $*"; }
warn()    { echo -e "${YELLOW}[WARN]${RESET}  $*"; }
error()   { echo -e "${RED}[ERROR]${RESET} $*" >&2; }
header()  { echo -e "\n${BOLD}${BLUE}══════════════════════════════════════════${RESET}"; \
            echo -e "${BOLD}${BLUE}  $*${RESET}"; \
            echo -e "${BOLD}${BLUE}══════════════════════════════════════════${RESET}"; }

# ── Dependency check ──────────────────────────────────────────────────────────
require() {
  command -v "$1" &>/dev/null || { error "Required tool not found: $1  (install it and retry)"; exit 1; }
}

# ── Repository definitions ────────────────────────────────────────────────────
# Format: "NAME|GITHUB_REPO|INSTALL_DIR|INSTALL_TYPE"
# INSTALL_TYPE: skills_copy | skills_submodule | workspace_clone | plugin_skill
declare -a REPOS=(
  "Marketing Skills (Corey Haines)|coreyhaines31/marketingskills|.claude/skills|skills_copy"
  "Claude SEO (AgriciDaniel)|AgriciDaniel/claude-seo|.claude/skills/seo-suite|install_sh"
  "AI Marketing Suite (Zubair)|zubair-trabzada/ai-marketing-claude|.claude/skills/ai-marketing|skills_copy"
  "Frontend Design (Anthropic)|anthropics/claude-code|.claude/skills/frontend-design|frontend_skill"
  "SEO Machine (TheCraigHewitt)|TheCraigHewitt/seomachine|seomachine|workspace_clone"
)

CACHE_DIR="${HOME}/.cache/claude-marketing-skills"
mkdir -p "$CACHE_DIR"

# ── Auto-detect mode ──────────────────────────────────────────────────────────
detect_mode() {
  local name="$1" repo="$2" dest="$3"
  local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"

  if [[ -f "$cache_marker" ]]; then
    echo "update"
  elif [[ -d "$dest" ]] && { git -C "$dest" rev-parse --git-dir &>/dev/null 2>&1; }; then
    echo "update"
  elif [[ -d "$dest" ]] && [[ -n "$(ls -A "$dest" 2>/dev/null)" ]]; then
    echo "update"
  else
    echo "install"
  fi
}

# ── Installation methods ──────────────────────────────────────────────────────

# Copy skills/ folder into .claude/skills/
do_skills_copy() {
  local name="$1" repo="$2" dest="$3" mode="$4"
  local tmp="${CACHE_DIR}/tmp_$(echo "$repo" | tr '/' '_')"
  local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"

  mkdir -p "$dest"

  if [[ "$mode" == "update" ]] && [[ -d "$tmp" ]]; then
    info "Pulling latest from github.com/$repo …"
    git -C "$tmp" pull --ff-only --quiet 2>/dev/null || {
      warn "Pull failed, re-cloning …"
      rm -rf "$tmp"
      git clone --depth 1 "https://github.com/$repo.git" "$tmp" --quiet
    }
  else
    info "Cloning github.com/$repo …"
    rm -rf "$tmp"
    git clone --depth 1 "https://github.com/$repo.git" "$tmp" --quiet
  fi

  # Copy skills sub-directory if it exists, otherwise copy root md files
  if [[ -d "$tmp/skills" ]]; then
    cp -r "$tmp/skills"/. "$dest/"
    success "Copied skills/ → $dest/"
  else
    # Flat copy of SKILL.md files
    find "$tmp" -maxdepth 2 -name "SKILL.md" -exec cp --parents {} "$dest/" \; 2>/dev/null || true
    success "Copied SKILL.md files → $dest/"
  fi

  touch "$cache_marker"
  echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$cache_marker"
}

# Run upstream install.sh (claude-seo)
do_install_sh() {
  local name="$1" repo="$2" dest="$3" mode="$4"
  local tmp="${CACHE_DIR}/tmp_$(echo "$repo" | tr '/' '_')"
  local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"

  if [[ "$mode" == "update" ]] && [[ -d "$tmp" ]]; then
    info "Pulling latest from github.com/$repo …"
    git -C "$tmp" pull --ff-only --quiet 2>/dev/null || {
      warn "Pull failed, re-cloning …"
      rm -rf "$tmp"
      git clone --depth 1 "https://github.com/$repo.git" "$tmp" --quiet
    }
  else
    info "Cloning github.com/$repo …"
    rm -rf "$tmp"
    git clone --depth 1 "https://github.com/$repo.git" "$tmp" --quiet
  fi

  if [[ -f "$tmp/install.sh" ]]; then
    info "Running install.sh for $name …"
    (cd "$tmp" && bash install.sh 2>&1 | sed 's/^/  /')
  else
    # Fallback: copy skill folders
    mkdir -p "$dest"
    cp -r "$tmp"/. "$dest/"
    info "install.sh not found - copied repo to $dest"
  fi

  touch "$cache_marker"
  echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$cache_marker"
}

# Pull only the frontend-design plugin folder from anthropics/claude-code
do_frontend_skill() {
  local name="$1" repo="$2" dest="$3" mode="$4"
  local tmp="${CACHE_DIR}/tmp_$(echo "$repo" | tr '/' '_')"
  local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"
  local skill_path="plugins/frontend-design/skills/frontend-design"

  # Use sparse-checkout to avoid cloning the entire claude-code repo
  if [[ "$mode" == "update" ]] && [[ -d "$tmp" ]]; then
    info "Pulling latest frontend-design skill …"
    git -C "$tmp" pull --ff-only --quiet 2>/dev/null || {
      warn "Pull failed, re-cloning …"
      rm -rf "$tmp"
      _sparse_clone "$repo" "$tmp" "$skill_path"
    }
  else
    info "Sparse-cloning frontend-design from github.com/$repo …"
    rm -rf "$tmp"
    _sparse_clone "$repo" "$tmp" "$skill_path"
  fi

  mkdir -p "$dest"
  if [[ -d "$tmp/$skill_path" ]]; then
    cp -r "$tmp/$skill_path"/. "$dest/"
    success "Copied frontend-design skill → $dest/"
  else
    warn "Skill path not found inside clone, copying root instead"
    cp -r "$tmp"/. "$dest/"
  fi

  touch "$cache_marker"
  echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$cache_marker"
}

_sparse_clone() {
  local repo="$1" dest="$2" subpath="$3"
  git clone --depth 1 --filter=blob:none --sparse \
    "https://github.com/$repo.git" "$dest" --quiet
  git -C "$dest" sparse-checkout set "$subpath" --quiet 2>/dev/null || \
    git -C "$dest" checkout --quiet  # fallback for older git
}

# Clone entire workspace (seomachine) - it IS the project, not just skills
do_workspace_clone() {
  local name="$1" repo="$2" dest="$3" mode="$4"
  local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"

  if [[ "$mode" == "update" ]] && [[ -d "$dest/.git" ]]; then
    info "Pulling latest $name workspace …"
    git -C "$dest" pull --ff-only --quiet 2>/dev/null || \
      warn "Could not auto-pull $name (local changes?). Run 'git pull' manually in $dest/"
  elif [[ "$mode" == "update" ]] && [[ -d "$dest" ]]; then
    warn "$dest exists but is not a git repo. Skipping re-clone to preserve your context files."
    warn "To reset: rm -rf $dest && re-run this script."
    return 0
  else
    info "Cloning $name workspace to ./$dest …"
    git clone --depth 1 "https://github.com/$repo.git" "$dest" --quiet
    info "Next step: fill in $dest/context/ with your brand details"
  fi

  touch "$cache_marker"
  echo "$(date -u +%Y-%m-%dT%H:%M:%SZ)" > "$cache_marker"
}

# ── Process one repo ──────────────────────────────────────────────────────────
process_repo() {
  local entry="$1" force_mode="${2:-auto}"
  IFS='|' read -r name repo dest install_type <<< "$entry"

  local mode
  if [[ "$force_mode" == "auto" ]]; then
    mode=$(detect_mode "$name" "$repo" "$dest")
  else
    mode="$force_mode"
  fi

  echo -e "\n${BOLD}▶ $name${RESET}  ${YELLOW}[$mode]${RESET}"
  echo   "  repo: github.com/$repo"
  echo   "  dest: ./$dest"

  case "$install_type" in
    skills_copy)     do_skills_copy    "$name" "$repo" "$dest" "$mode" ;;
    install_sh)      do_install_sh     "$name" "$repo" "$dest" "$mode" ;;
    frontend_skill)  do_frontend_skill "$name" "$repo" "$dest" "$mode" ;;
    workspace_clone) do_workspace_clone "$name" "$repo" "$dest" "$mode" ;;
    *)
      error "Unknown install type: $install_type"; return 1 ;;
  esac
}

# ── Usage ──────────────────────────────────────────────────────────────────────
usage() {
  local self; self=$(basename "$0")
  echo -e "${BOLD}Usage:${RESET}"
  echo -e "  $self [OPTIONS] [SKILL_NUMBERS...]"
  echo
  echo -e "${BOLD}Options:${RESET}"
  echo    "  (no args)        Auto-detect: install new, update existing"
  echo    "  --install        Force fresh install of all skills"
  echo    "  --update         Force update of all skills"
  echo    "  --list           List available skills with their status"
  echo    "  --help           Show this help"
  echo
  echo -e "${BOLD}Skill numbers (optional):${RESET}"
  echo    "  1  Marketing Skills by Corey Haines (30+ CRO/SEO/copy skills)"
  echo    "  2  Claude SEO - AgriciDaniel (13 sub-skills, 7 subagents)"
  echo    "  3  AI Marketing Suite - Zubair (15 skills, PDF reports)"
  echo    "  4  Frontend Design - Anthropic official (277k+ installs)"
  echo    "  5  SEO Machine workspace - TheCraigHewitt (full content workspace)"
  echo
  echo -e "${BOLD}Examples:${RESET}"
  echo    "  $self               # auto-detect & run all"
  echo    "  $self --update      # force-update all"
  echo    "  $self 1 4           # auto-detect skills 1 and 4 only"
  echo    "  $self --install 2   # fresh install skill 2 only"
  echo
}

# ── List status ────────────────────────────────────────────────────────────────
list_skills() {
  header "Available Marketing Skills"
  local i=1
  for entry in "${REPOS[@]}"; do
    IFS='|' read -r name repo dest _ <<< "$entry"
    local cache_marker="${CACHE_DIR}/$(echo "$repo" | tr '/' '_').installed"
    local status_str="${RED}not installed${RESET}"
    if [[ -f "$cache_marker" ]]; then
      local ts; ts=$(cat "$cache_marker")
      status_str="${GREEN}installed${RESET} (last: $ts)"
    elif [[ -d "$dest" ]] && [[ -n "$(ls -A "$dest" 2>/dev/null)" ]]; then
      status_str="${YELLOW}present (untracked)${RESET}"
    fi
    echo -e "  ${BOLD}$i.${RESET} $name"
    echo -e "     repo: github.com/$repo"
    echo -e "     dest: ./$dest"
    echo -e "     status: $status_str"
    echo
    ((i++))
  done
}

# ── Main ───────────────────────────────────────────────────────────────────────
main() {
  require git

  header "Claude Code Marketing Skills Installer"

  local mode="auto"
  local -a selected_indices=()

  # Parse arguments
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --install) mode="install"; shift ;;
      --update)  mode="update";  shift ;;
      --list)    list_skills; exit 0 ;;
      --help|-h) usage; exit 0 ;;
      [1-5])     selected_indices+=("$1"); shift ;;
      *)         error "Unknown argument: $1"; usage; exit 1 ;;
    esac
  done

  # If no specific skills selected, run all
  if [[ ${#selected_indices[@]} -eq 0 ]]; then
    selected_indices=(1 2 3 4 5)
  fi

  local total=${#selected_indices[@]}
  local done_count=0
  local failed=()

  for idx in "${selected_indices[@]}"; do
    local repo_entry="${REPOS[$((idx-1))]}"
    if [[ -z "$repo_entry" ]]; then
      error "Invalid skill number: $idx (valid: 1-5)"; continue
    fi
    if process_repo "$repo_entry" "$mode"; then
      ((done_count++))
    else
      IFS='|' read -r name _ <<< "$repo_entry"
      failed+=("$name")
    fi
  done

  # Summary
  header "Summary"
  success "$done_count / $total skills processed successfully"
  if [[ ${#failed[@]} -gt 0 ]]; then
    error "Failed: ${failed[*]}"
    exit 1
  fi

  echo
  info "Skills installed to .claude/skills/  - Claude Code picks them up automatically."
  info "SEO Machine workspace cloned to ./seomachine/  - open with: claude-code ./seomachine"
  info ""
  info "Run '$(basename "$0") --list' at any time to check install status."
  info "Run '$(basename "$0") --update' to refresh all skills to latest."
  echo
}

main "$@"
