#!/usr/bin/env bash
# setup.sh - Claude Code bootstrap for macOS / Linux
# Usage:
#   curl -fsSL https://gist.githubusercontent.com/YOUR_GIST_URL/raw/setup.sh | bash
#
# Or with parameters:
#   CC_API_KEY="sk-ant-..." CC_REPO="https://github.com/org/repo" bash <(curl -fsSL https://gist.../raw/setup.sh)

set -e

CYAN='\033[0;36m'
GREEN='\033[0;32m'
RED='\033[0;31m'
GRAY='\033[0;90m'
NC='\033[0m'

step() { echo -e "\n${CYAN}[SETUP] $1${NC}"; }
ok()   { echo -e "  ${GREEN}OK: $1${NC}"; }
fail() { echo -e "  ${RED}ERR: $1${NC}"; exit 1; }
skip() { echo -e "  ${GRAY}SKIP: $1${NC}"; }

echo ""
echo -e "${CYAN}  Claude Code Bootstrap - X9.cz"
echo -e "  ==============================${NC}"
echo ""

# ------------------------------------------------------------
# API KEY
# ------------------------------------------------------------
API_KEY="${CC_API_KEY:-}"
if [ -z "$API_KEY" ]; then
    read -rsp "Enter Anthropic API key (sk-ant-...): " API_KEY
    echo ""
fi
if [[ ! "$API_KEY" == sk-* ]]; then
    fail "Invalid API key"
fi

# ------------------------------------------------------------
# REPO URL
# ------------------------------------------------------------
REPO_URL="${CC_REPO:-}"
if [ -z "$REPO_URL" ]; then
    read -rp "Enter repo URL (https://github.com/org/repo): " REPO_URL
fi
if [ -z "$REPO_URL" ]; then
    fail "No repo URL provided"
fi

WORK_DIR="${CC_WORKDIR:-$HOME/Projects}"

# ------------------------------------------------------------
# DETECT OS
# ------------------------------------------------------------
OS="$(uname -s)"
step "Detected OS: $OS"

# ------------------------------------------------------------
# NODE.JS
# ------------------------------------------------------------
step "Checking Node.js..."

node_ok=false
if command -v node &>/dev/null; then
    NODE_VER=$(node --version | sed 's/v//' | cut -d. -f1)
    if [ "$NODE_VER" -ge 18 ]; then
        ok "Node.js $(node --version)"
        node_ok=true
    fi
fi

if [ "$node_ok" = false ]; then
    step "Installing Node.js..."
    case "$OS" in
        Darwin)
            if command -v brew &>/dev/null; then
                brew install node
            else
                step "Installing Homebrew first..."
                /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
                brew install node
            fi
            ;;
        Linux)
            # Node via NodeSource
            curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
            if command -v apt-get &>/dev/null; then
                sudo apt-get install -y nodejs
            elif command -v dnf &>/dev/null; then
                sudo dnf install -y nodejs
            elif command -v yum &>/dev/null; then
                sudo yum install -y nodejs
            else
                fail "Cannot detect package manager. Install Node.js manually: https://nodejs.org"
            fi
            ;;
        *)
            fail "Unsupported OS: $OS. Install Node.js manually: https://nodejs.org"
            ;;
    esac
    ok "Node.js installed"
fi

# ------------------------------------------------------------
# GIT
# ------------------------------------------------------------
step "Checking Git..."

if command -v git &>/dev/null; then
    ok "Git available"
else
    step "Installing Git..."
    case "$OS" in
        Darwin)  brew install git ;;
        Linux)
            if command -v apt-get &>/dev/null; then sudo apt-get install -y git
            elif command -v dnf &>/dev/null; then sudo dnf install -y git
            elif command -v yum &>/dev/null; then sudo yum install -y git
            else fail "Cannot install Git automatically"
            fi
            ;;
    esac
    ok "Git installed"
fi

# ------------------------------------------------------------
# CLAUDE CODE
# ------------------------------------------------------------
step "Checking Claude Code..."

if command -v claude &>/dev/null; then
    ok "Claude Code $(claude --version)"
else
    step "Installing Claude Code..."
    npm install -g @anthropic-ai/claude-code
    ok "Claude Code installed"
fi

# ------------------------------------------------------------
# API KEY - ulozit
# ------------------------------------------------------------
step "Saving API key..."

SHELL_RC=""
case "$SHELL" in
    */zsh)  SHELL_RC="$HOME/.zshrc" ;;
    */bash)
        if [ "$OS" = "Darwin" ]; then
            SHELL_RC="$HOME/.bash_profile"
        else
            SHELL_RC="$HOME/.bashrc"
        fi
        ;;
    *) SHELL_RC="$HOME/.profile" ;;
esac

# Odstrante stary zaznam pokud existuje
if [ -f "$SHELL_RC" ]; then
    grep -v 'ANTHROPIC_API_KEY' "$SHELL_RC" > "${SHELL_RC}.tmp" && mv "${SHELL_RC}.tmp" "$SHELL_RC"
fi

echo "export ANTHROPIC_API_KEY=\"$API_KEY\"" >> "$SHELL_RC"
export ANTHROPIC_API_KEY="$API_KEY"
unset CC_API_KEY
ok "API key saved to $SHELL_RC"

# ------------------------------------------------------------
# CLONE / PULL REPO
# ------------------------------------------------------------
step "Setting up repository..."
mkdir -p "$WORK_DIR"

REPO_NAME=$(basename "$REPO_URL" .git)
TARGET_PATH="$WORK_DIR/$REPO_NAME"

if [ -d "$TARGET_PATH/.git" ]; then
    step "Repo exists, pulling latest..."
    git -C "$TARGET_PATH" pull
else
    git clone "$REPO_URL" "$TARGET_PATH"
    ok "Cloned to $TARGET_PATH"
fi

# ------------------------------------------------------------
# CLEAN SHELL HISTORY - odstranit radky s API key
# ------------------------------------------------------------
HIST_FILE="${HISTFILE:-$HOME/.bash_history}"
if [ -f "$HIST_FILE" ]; then
    grep -v 'sk-ant-\|CC_API_KEY\|ANTHROPIC' "$HIST_FILE" > "${HIST_FILE}.tmp" && mv "${HIST_FILE}.tmp" "$HIST_FILE"
fi
# zsh history
ZSH_HIST="$HOME/.zsh_history"
if [ -f "$ZSH_HIST" ]; then
    grep -v 'sk-ant-\|CC_API_KEY\|ANTHROPIC' "$ZSH_HIST" > "${ZSH_HIST}.tmp" && mv "${ZSH_HIST}.tmp" "$ZSH_HIST"
fi

# ------------------------------------------------------------
# LAUNCH
# ------------------------------------------------------------
echo ""
echo -e "${GREEN}  =============================="
echo -e "  Ready! Repo: $TARGET_PATH"
echo -e "  ==============================${NC}"
echo ""
echo -e "  Run: ${CYAN}source $SHELL_RC && cd $TARGET_PATH && claude${NC}"
echo ""

# Pokud je skript spusten primo (ne pres pipe), rovnou spustit
if [ -t 0 ]; then
    cd "$TARGET_PATH"
    # shellcheck disable=SC1090
    source "$SHELL_RC"
    claude
fi
