#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────────
#  codeably — shortcut installer
#  Adds `cb` alias so you can type: cb "your task"
#  Works on macOS, Linux, and Windows (Git Bash / WSL)
# ─────────────────────────────────────────────────────────────────

set -euo pipefail

CYAN='\033[38;5;43m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BOLD='\033[1m'
DIM='\033[2m'
RESET='\033[0m'

ok()   { echo -e "${GREEN}  ✓ $*${RESET}"; }
info() { echo -e "${CYAN}  · $*${RESET}"; }
warn() { echo -e "${YELLOW}  ⚠ $*${RESET}"; }
err()  { echo -e "${RED}  ✕ $*${RESET}"; }

echo ""
echo -e "${CYAN}${BOLD}  ╭──────────────────────────────────────╮${RESET}"
echo -e "${CYAN}${BOLD}  │  codeably shortcut installer         │${RESET}"
echo -e "${CYAN}${BOLD}  ╰──────────────────────────────────────╯${RESET}"
echo ""

# ── Detect shell rc file ───────────────────────────────────────────────────
detect_rc() {
  # Try to find the active shell config
  if [[ -n "${ZSH_VERSION:-}" || "$SHELL" == */zsh ]]; then
    echo "$HOME/.zshrc"
  elif [[ -n "${BASH_VERSION:-}" || "$SHELL" == */bash ]]; then
    if [[ -f "$HOME/.bash_profile" ]]; then
      echo "$HOME/.bash_profile"
    else
      echo "$HOME/.bashrc"
    fi
  elif [[ "$SHELL" == */fish ]]; then
    echo "$HOME/.config/fish/config.fish"
  else
    echo "$HOME/.bashrc"
  fi
}

ALIAS_LINE='alias cb="codeably"'
FISH_LINE='alias cb "codeably"'

# ── Check codeably is installed ────────────────────────────────────────────
if ! command -v codeably &>/dev/null; then
  warn "codeably not found in PATH."
  info "Install it first: npm install -g codeably"
  echo ""
fi

RC_FILE=$(detect_rc)
SHELL_NAME=$(basename "${SHELL:-bash}")

echo -e "  ${DIM}Shell detected:  ${SHELL_NAME}${RESET}"
echo -e "  ${DIM}Config file:     ${RC_FILE}${RESET}"
echo ""

# ── Fish shell uses different alias syntax ─────────────────────────────────
if [[ "$SHELL_NAME" == "fish" ]]; then
  if grep -q 'alias cb' "$RC_FILE" 2>/dev/null; then
    ok "alias 'cb' already exists in $RC_FILE"
  else
    echo "$FISH_LINE" >> "$RC_FILE"
    ok "Added 'cb' alias to $RC_FILE"
  fi
else
  if grep -q "alias cb=" "$RC_FILE" 2>/dev/null; then
    ok "alias 'cb' already exists in $RC_FILE"
  else
    echo "" >> "$RC_FILE"
    echo "# codeably shortcut — added by install-shortcut.sh" >> "$RC_FILE"
    echo "$ALIAS_LINE" >> "$RC_FILE"
    ok "Added 'cb' alias to $RC_FILE"
  fi
fi

echo ""
echo -e "  ${BOLD}Reload your shell to activate:${RESET}"
echo -e "  ${CYAN}  source ${RC_FILE}${RESET}"
echo -e "  ${DIM}  or open a new terminal window${RESET}"
echo ""
echo -e "  ${BOLD}Then use:${RESET}"
echo -e "  ${CYAN}  cb \"add unit tests to src/utils.js\"${RESET}"
echo -e "  ${CYAN}  cb config${RESET}"
echo -e "  ${CYAN}  cb review${RESET}"
echo ""
