#!/bin/bash

# Complete post-configure installation script
# Supported OS: Ubuntu, OpenSUSE (and Debian)
#
# Full install (classic profile - default):
#   curl -sLS https://get.chavkov.com/index.sh | bash
#
# Minimal profile (mise-based, no containers):
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --profile minimal
#
# Single-script execution (downloads tarball, runs one script):
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script <SCRIPT_NAME>
#   Example: curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 02-pyenv.sh
#
# Profiles:
#   --profile classic   Full installation with brew, pyenv, fnm, arkade, podman (default)
#   --profile minimal   Lightweight mise-based runtimes, no containers
#
# Preset flags (convenience shortcuts):
#   --github-ssh    Run first available GitHub SSH script (80–83)
#                   (writes Host github.com with IdentityAgent none — avoids "agent refused" on fresh OS)
#   --claude        Run 22-claude.sh (brew claude-code + ~/.claude/settings.json with Vertex env)
#   --aliases       Run 01-shell-aliases.sh (~/.aliases)
#   --byobu         Run 18-byobu.sh
#   --tmux          Run 19-tmux.sh
#   --tmux-config   Run 38-tmux-config.sh (prepare tmux helpers/theme only)
#   --bin-scripts   Run 20-bin-scripts.sh (installs b, d-ip, d-run, d-rc, d-ri, d-rn, d-rv, d-nuke to ~/.local/bin)
#   --rtk           Run 25-rtk.sh (rtk CLI for LLM token reduction)
#   --docker        Run 26-docker.sh (Docker daemon with internal registry)
#   --docker-install Run 08-docker-install-ubuntu.sh (Install Docker on Ubuntu/Debian)
#   --playwright    Run 27-playwright-deps.sh (Playwright system dependencies)
#   --dist-upgrade  Run 00-dist-upgrade.sh (Full system dist-upgrade)
#   --brain         Run 90-brain.sh (Clone 2nd-brain to ~/.config/brain)
#   --krew          Run 31-krew.sh (krew kubectl plugin manager + ns, ctx plugins)
#   --copilot       Run 34-copilot.sh (GitHub Copilot CLI via npm)
#   --ai-cli-tools  Run 23-ai-cli-tools.sh (Cursor, Codex, Gemini, Pi coding agent)
#   --claude-profiles [profile]  Run 35-claude-profiles.sh (Claude profile switcher for bosch/sap)
#   --claude-backup-clean Run 36-claude-backup-clean.sh (install backup cleanup to ~/.local/bin)
#
# Individual scripts (--script SCRIPT_NAME or run from extracted tarball):
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --bin-scripts
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 01-shell-aliases.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 02-pyenv.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 05-fnm.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 05-fzf.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 07-arkade.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 10-git.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 11-neovim.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 15-brew.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 16-kind-rootless-podman.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 17-gh.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 18-byobu.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 19-tmux.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 20-bin-scripts.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 22-claude.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 25-rtk.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 31-krew.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 33-framework-tool-tui.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 34-copilot.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 23-ai-cli-tools.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 35-claude-profiles.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 36-claude-backup-clean.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 80-github_vchavkov.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 82-github_vchavkov82.sh
#   curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 83-github_ns9-io.sh
#
# Or download tarball and run any script locally:
#   curl -sLS https://get.chavkov.com/scripts.tar.gz | tar -xzf -
#   bash scripts/02-pyenv.sh
#   bash scripts/10-git.sh
#   # etc.
#
# External standalone scripts (not in tarball; run from repo or curl):

#   Bin scripts:    curl -sLS https://get.chavkov.com/index.sh | bash -s -- --bin-scripts
#                   (installs b, d-ip, d-run, d-rc, d-ri, d-rn, d-rv, d-nuke to ~/.local/bin)

#   Mise:           curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 04-mise.sh
#                   (installs mise + python, node, go; adds yarn/npm/node aliases via mise exec)

#   Linux utils:    curl -sLS https://get.chavkov.com/index.sh | bash -s -- --script 12-utilities-brew.sh
#                   (bat, eza, fd, rg, fzf, jq, yq, htop, tldr, tree, watch via brew)

#   GitHub SSH:     curl -sLS https://get.chavkov.com/github-ssh-reconfig.sh | bash
#   Test GitHub:    ssh -T git@github.com   # expect "Hi <user>!" (no "agent refused" / Permission denied)

#   Claude profiles: curl -sLS https://get.chavkov.com/index.sh | bash -s -- --claude-profiles
#                    curl -sLS https://get.chavkov.com/index.sh | bash -s -- --claude-profiles sap
#                    (installs claude-profile function; optional profile arg sets the active profile)
#
#   Tmux config:     curl -sLS https://get.chavkov.com/index.sh | bash -s -- --tmux-config
#                    (prepares tmux helper keybindings, saved sessions, and Catppuccin theme)

set -euo pipefail

# Parse profile flag (must be done before other flag parsing)
PROFILE="classic"
_PROFILE_ARG_SHIFT=0
if [[ "${1:-}" == "--profile" ]]; then
    PROFILE="${2:-classic}"
    _PROFILE_ARG_SHIFT=2
    shift 2 2>/dev/null || true
elif [[ "${1:-}" == --profile=* ]]; then
    PROFILE="${1#--profile=}"
    _PROFILE_ARG_SHIFT=1
    shift 1 2>/dev/null || true
fi

# Validate profile
case "$PROFILE" in
    classic|minimal) ;;
    *)
        echo "❌ Invalid profile: $PROFILE (valid: classic, minimal)"
        exit 1
        ;;
esac

# Skip Playwright preamble for single-script or shortcut-flag modes (avoids
# zypper lock conflicts and unnecessary installs for unrelated scripts).
# Also skip for minimal profile (no Playwright deps needed)
_PREAMBLE_SKIP=false
case "${1:-}" in
    --script|--github-ssh|--claude|--aliases|--byobu|--tmux|--tmux-config|--bin-scripts|--rtk|--docker|--docker-install|--playwright|--dist-upgrade|--brain|--krew|--copilot|--ai-cli-tools|--claude-profiles|--claude-backup-clean)
        _PREAMBLE_SKIP=true ;;
esac
if [[ "$PROFILE" == "minimal" ]]; then
    _PREAMBLE_SKIP=true
fi

# Install browser/media/runtime dependencies up front (Playwright/system libs).
if [ "$_PREAMBLE_SKIP" = false ] && [ -r /etc/os-release ]; then
    . /etc/os-release
    _OS_ID="${ID:-}"
    _OS_ID_LIKE=" ${ID_LIKE:-} "
    case "${_OS_ID}" in
        ubuntu|debian)
            _OS_PREAMBLE_FAMILY="debian"
            ;;
        opensuse-leap|opensuse-tumbleweed|opensuse|suse|sles)
            _OS_PREAMBLE_FAMILY="opensuse"
            ;;
        *)
            case "${_OS_ID_LIKE}" in
                *" ubuntu "*|*" debian "*) _OS_PREAMBLE_FAMILY="debian" ;;
                *" suse "*|*" opensuse "*) _OS_PREAMBLE_FAMILY="opensuse" ;;
                *) _OS_PREAMBLE_FAMILY="" ;;
            esac
            ;;
    esac
    case "${_OS_PREAMBLE_FAMILY}" in
        debian)
            echo "📦 Installing Ubuntu/Debian Playwright dependencies..."
            sudo apt-get update -y || true

            # Core packages (available on both Ubuntu and Debian)
            sudo apt-get install -y --no-install-recommends \
                libicu-dev \
                libxml2 \
                libxslt1.1 \
                gstreamer1.0-plugins-good \
                gstreamer1.0-plugins-bad \
                gstreamer1.0-libav \
                libgstreamer-plugins-bad1.0-0 \
                libflite1 \
                libhyphen0 \
                libmanette-0.2-0 \
                libwoff1 \
                libgles2 \
                libenchant-2-2 \
                libwebpdemux2 \
                libwebpmux3 \
                xvfb \
                fonts-noto-color-emoji \
                fonts-liberation \
                xfonts-base || true

            # Version-specific packages (differ between Ubuntu/Debian versions)
            # Try multiple versions, install whichever is available
            sudo apt-get install -y --no-install-recommends libavif16 2>/dev/null \
                || sudo apt-get install -y --no-install-recommends libavif15 2>/dev/null \
                || sudo apt-get install -y --no-install-recommends libavif-dev 2>/dev/null \
                || true

            sudo apt-get install -y --no-install-recommends libx264-163 2>/dev/null \
                || sudo apt-get install -y --no-install-recommends libx264-164 2>/dev/null \
                || sudo apt-get install -y --no-install-recommends libx264-dev 2>/dev/null \
                || true
            ;;
        opensuse)
            echo "📦 Installing OpenSUSE base + media/font dependencies..."
            opensuse_pkg_exists() {
                local pkg="${1:?}"
                zypper -n se --match-exact "$pkg" | awk 'NR>4 { found=1 } END { exit(!found) }'
            }

            opensuse_add_first_available() {
                local selected=""
                for candidate in "$@"; do
                    if opensuse_pkg_exists "$candidate"; then
                        selected="$candidate"
                        break
                    fi
                done

                if [ -n "$selected" ]; then
                    OPEN_SUSE_PKGS+=("$selected")
                else
                    echo "⚠️  No package candidate found for: $*"
                fi
            }

            OPEN_SUSE_PKGS=()
            opensuse_add_first_available mozilla-nspr
            opensuse_add_first_available mozilla-nss
            opensuse_add_first_available libatk-1_0-0
            opensuse_add_first_available libatspi0 libatspi0-0
            opensuse_add_first_available gtk2 libgtk-2_0-0
            opensuse_add_first_available gtk3 libgtk-3-0
            opensuse_add_first_available at-spi2-core
            opensuse_add_first_available libcups2 libcups2-2 cups-libs
            opensuse_add_first_available libdrm2
            opensuse_add_first_available libdbus-1-3 dbus-1
            opensuse_add_first_available libxkbcommon0 libxkbcommon0-0
            opensuse_add_first_available libX11-6 libx11-6
            opensuse_add_first_available libXcomposite1 libxcomposite1
            opensuse_add_first_available libXdamage1 libxdamage1
            opensuse_add_first_available libXext6 libxext6
            opensuse_add_first_available libXfixes3 libxfixes3
            opensuse_add_first_available libXrandr2 libxrandr2
            opensuse_add_first_available libxcb1 libxcb1-1
            opensuse_add_first_available libxshmfence1
            opensuse_add_first_available libXrender1 libxrender1
            opensuse_add_first_available libpango-1_0-0 pango-tools
            opensuse_add_first_available libgbm1
            opensuse_add_first_available alsa-lib libasound2
            opensuse_add_first_available libicu76 libicu78 libicu77 libicu75 icu
            opensuse_add_first_available libxml2 libxml2-16
            opensuse_add_first_available libxslt1
            opensuse_add_first_available gstreamer-plugins-good
            opensuse_add_first_available gstreamer-plugins-bad
            opensuse_add_first_available gstreamer-plugins-libav
            opensuse_add_first_available libgstcodecparsers-1_0-0
            opensuse_add_first_available libgstfft-1_0-0
            opensuse_add_first_available flite-devel
            opensuse_add_first_available libhyphen0
            opensuse_add_first_available libmanette-0_2-0
            opensuse_add_first_available libavif16
            opensuse_add_first_available libwoff2dec1 libwoff2dec1_0_2
            opensuse_add_first_available Mesa-libGLESv2-2 Mesa-libGLESv2 libGLESv2-2 libGLESv2-3 libGLESv2
            opensuse_add_first_available libenchant-2-2
            opensuse_add_first_available libwebpdemux2
            opensuse_add_first_available libwebpmux3
            opensuse_add_first_available libx264-163 libx264-164 libx264-165 libx264-166 libx264-167 x264
            opensuse_add_first_available chromium chromium-browser
            opensuse_add_first_available MozillaFirefox firefox
            opensuse_add_first_available xorg-x11-server
            opensuse_add_first_available xorg-x11-server-Xvfb
            opensuse_add_first_available xauth xorg-x11-xauth
            opensuse_add_first_available xhost
            opensuse_add_first_available xdpyinfo
            opensuse_add_first_available xrandr
            opensuse_add_first_available xset
            opensuse_add_first_available noto-coloremoji-fonts google-noto-coloremoji-fonts
            opensuse_add_first_available liberation-fonts
            opensuse_add_first_available xorg-x11-fonts

            if [ "${#OPEN_SUSE_PKGS[@]}" -gt 0 ]; then
                sudo zypper --non-interactive install -y "${OPEN_SUSE_PKGS[@]}" || true
            else
                echo "⚠️  No OpenSUSE dependency packages resolved for installation"
            fi
            ;;
    esac
    unset _OS_ID _OS_ID_LIKE _OS_PREAMBLE_FAMILY
fi

# Check for GitHub SSH reconfiguration flag
GITHUB_SSH_RECONFIG=false
if [[ "${1:-}" == "--github-ssh" ]]; then
    GITHUB_SSH_RECONFIG=true
fi

# Check for Claude settings reconfiguration flag
CLAUDE_RECONFIG=false
if [[ "${1:-}" == "--claude" ]]; then
    CLAUDE_RECONFIG=true
fi

# Check for aliases reconfiguration flag
ALIASES_RECONFIG=false
if [[ "${1:-}" == "--aliases" ]]; then
    ALIASES_RECONFIG=true
fi

# Check for Byobu-only flag
BYOBU_ONLY=false
if [[ "${1:-}" == "--byobu" ]]; then
    BYOBU_ONLY=true
fi

# Check for Tmux-only flag
TMUX_ONLY=false
if [[ "${1:-}" == "--tmux" ]]; then
    TMUX_ONLY=true
fi

# Check for tmux config-only flag
TMUX_CONFIG_ONLY=false
if [[ "${1:-}" == "--tmux-config" ]]; then
    TMUX_CONFIG_ONLY=true
fi

# Check for bin-scripts flag (installs b, gw-add, gw-rm, etc.)
BIN_SCRIPTS_ONLY=false
if [[ "${1:-}" == "--bin-scripts" ]]; then
    BIN_SCRIPTS_ONLY=true
fi

# Check for rtk flag (LLM token reduction CLI)
RTK_ONLY=false
if [[ "${1:-}" == "--rtk" ]]; then
    RTK_ONLY=true
fi

# Check for docker flag (Docker daemon configuration)
DOCKER_ONLY=false
if [[ "${1:-}" == "--docker" ]]; then
    DOCKER_ONLY=true
fi

# Check for docker-install flag (Install Docker on Ubuntu/Debian)
DOCKER_INSTALL_ONLY=false
if [[ "${1:-}" == "--docker-install" ]]; then
    DOCKER_INSTALL_ONLY=true
fi

# Check for playwright flag (Playwright system dependencies)
PLAYWRIGHT_ONLY=false
if [[ "${1:-}" == "--playwright" ]]; then
    PLAYWRIGHT_ONLY=true
fi

# Check for dist-upgrade flag
DIST_UPGRADE_ONLY=false
if [[ "${1:-}" == "--dist-upgrade" ]]; then
    DIST_UPGRADE_ONLY=true
fi

# Check for brain flag (2nd-brain repository)
BRAIN_ONLY=false
if [[ "${1:-}" == "--brain" ]]; then
    BRAIN_ONLY=true
fi

# Check for krew flag
KREW_ONLY=false
if [[ "${1:-}" == "--krew" ]]; then
    KREW_ONLY=true
fi

# Check for copilot flag (GitHub Copilot CLI)
COPILOT_ONLY=false
if [[ "${1:-}" == "--copilot" ]]; then
    COPILOT_ONLY=true
fi

# Check for ai-cli-tools flag (Cursor CLI + OpenAI Codex)
AI_CLI_TOOLS_ONLY=false
if [[ "${1:-}" == "--ai-cli-tools" ]]; then
    AI_CLI_TOOLS_ONLY=true
fi

# Check for claude-profiles flag (Claude profile switcher)
# Optional: --claude-profiles <profile> sets the active profile (bosch|sap)
CLAUDE_PROFILES_ONLY=false
CLAUDE_PROFILES_SET=""
if [[ "${1:-}" == "--claude-profiles" ]]; then
    CLAUDE_PROFILES_ONLY=true
    if [[ -n "${2:-}" && "${2:-}" != --* ]]; then
        CLAUDE_PROFILES_SET="${2}"
    fi
fi

# Check for claude-backup-clean flag
CLAUDE_BACKUP_CLEAN_ONLY=false
if [[ "${1:-}" == "--claude-backup-clean" ]]; then
    CLAUDE_BACKUP_CLEAN_ONLY=true
fi

# Check for single-script execution: --script SCRIPT_NAME
SCRIPT_ONLY=""
if [[ "${1:-}" == "--script" && -n "${2:-}" ]]; then
    SCRIPT_ONLY="${2}"
fi

echo "🚀 Starting optimized post-configure installation..."

# Create temporary working directory
TEMP_DIR="/tmp/post-configure-$$"
mkdir -p "$TEMP_DIR"
cd "$TEMP_DIR"

# Cleanup function
cleanup() {
    echo "🧹 Cleaning up temporary files..."
    rm -rf "$TEMP_DIR"
}
trap cleanup EXIT

# Download and extract scripts archive
echo "📦 Downloading and extracting scripts..."
SCRIPTS_URL="${POST_CONFIGURE_SCRIPTS_URL:-https://get.chavkov.com/scripts.tar.gz}"
if ! curl -sLSf "${SCRIPTS_URL}" | tar -xzf -; then
    echo "❌ Failed to download or extract scripts archive"
    echo "   Please check your internet connection and try again"
    exit 1
fi
if [ ! -d "./scripts" ]; then
    echo "❌ Failed to extract scripts directory"
    exit 1
fi

# Helper function to find scripts in order: common -> profile -> top-level
find_script() {
    local script_name="$1"
    local search_paths=(
        "./scripts/common/${script_name}"
        "./scripts/${PROFILE}/${script_name}"
        "./scripts/${script_name}"
    )
    for path in "${search_paths[@]}"; do
        if [ -f "$path" ]; then
            echo "$path"
            return 0
        fi
    done
    return 1
}

# Run a script by name (searches common -> profile -> top-level)
run_found_script() {
    local script_name="$1"
    local script_path
    if script_path=$(find_script "$script_name"); then
        bash "$script_path"
        return $?
    else
        echo "❌ Script not found: $script_name"
        return 1
    fi
}

# Handle reconfiguration options (prefer vchavkov82 as default)
if [ "$GITHUB_SSH_RECONFIG" = true ]; then
    echo "🔧 Running GitHub SSH reconfiguration..."
    if [ -f "./scripts/common/82-github_vchavkov82.sh" ]; then
        bash ./scripts/common/82-github_vchavkov82.sh
    elif [ -f "./scripts/82-github_vchavkov82.sh" ]; then
        bash ./scripts/82-github_vchavkov82.sh
    elif [ -f "./scripts/common/80-github_vchavkov.sh" ]; then
        bash ./scripts/common/80-github_vchavkov.sh
    elif [ -f "./scripts/80-github_vchavkov.sh" ]; then
        bash ./scripts/80-github_vchavkov.sh
    elif [ -f "./scripts/common/83-github_ns9-io.sh" ]; then
        bash ./scripts/common/83-github_ns9-io.sh
    elif [ -f "./scripts/83-github_ns9-io.sh" ]; then
        bash ./scripts/83-github_ns9-io.sh
    else
        echo "❌ GitHub SSH configuration scripts not found"
        echo "Available scripts:"
        echo "  - 82-github_vchavkov82.sh (default)"
        echo "  - 80-github_vchavkov.sh"
        echo "  - 83-github_ns9-io.sh"
        exit 1
    fi
elif [ "$CLAUDE_RECONFIG" = true ]; then
    echo "🤖 Running Claude settings reconfiguration..."
    run_found_script "22-claude.sh" || exit 1
elif [ "$ALIASES_RECONFIG" = true ]; then
    echo "🔧 Running aliases reconfiguration..."
    run_found_script "01-shell-aliases.sh" || exit 1
elif [ "$BYOBU_ONLY" = true ]; then
    echo "🖥️  Running Byobu setup only..."
    run_found_script "18-byobu.sh" || exit 1
elif [ "$TMUX_ONLY" = true ]; then
    echo "🖥️  Running Tmux setup only..."
    run_found_script "19-tmux.sh" || { echo "❌ Tmux script not found"; exit 1; }
elif [ "$TMUX_CONFIG_ONLY" = true ]; then
    echo "🖥️  Preparing Tmux config only..."
    run_found_script "38-tmux-config.sh" || { echo "❌ Tmux config script not found"; exit 1; }
elif [ "$BIN_SCRIPTS_ONLY" = true ]; then
    echo "📁 Running bin-scripts setup (b, d-ip, d-run, d-rc, d-ri, d-rn, d-rv, d-nuke)..."
    run_found_script "20-bin-scripts.sh" || exit 1
elif [ "$RTK_ONLY" = true ]; then
    echo "🚀 Running rtk setup (LLM token reduction CLI)..."
    run_found_script "25-rtk.sh" || exit 1
elif [ "$DOCKER_ONLY" = true ]; then
    echo "🐳 Running Docker daemon configuration..."
    run_found_script "26-docker.sh" || exit 1
elif [ "$DOCKER_INSTALL_ONLY" = true ]; then
    echo "🐳 Installing Docker on Ubuntu/Debian..."
    run_found_script "08-docker-install-ubuntu.sh" || exit 1
elif [ "$PLAYWRIGHT_ONLY" = true ]; then
    echo "🎭 Running Playwright dependencies installation..."
    run_found_script "27-playwright-deps.sh" || exit 1
elif [ "$DIST_UPGRADE_ONLY" = true ]; then
    echo "⬆️  Running system dist-upgrade..."
    run_found_script "00-dist-upgrade.sh" || exit 1
elif [ "$BRAIN_ONLY" = true ]; then
    echo "🧠 Cloning 2nd-brain repository..."
    run_found_script "90-brain.sh" || exit 1
elif [ "$KREW_ONLY" = true ]; then
    echo "🔌 Installing krew (kubectl plugin manager)..."
    run_found_script "31-krew.sh" || exit 1
elif [ "$COPILOT_ONLY" = true ]; then
    echo "🤖 Installing GitHub Copilot CLI..."
    run_found_script "34-copilot.sh" || exit 1
elif [ "$AI_CLI_TOOLS_ONLY" = true ]; then
    echo "🤖 Installing AI CLI tools (Cursor, Codex, Gemini, Pi)..."
    run_found_script "23-ai-cli-tools.sh" || exit 1
elif [ "$CLAUDE_PROFILES_ONLY" = true ]; then
    echo "🔧 Installing Claude profile switcher..."
    CLAUDE_PROFILE_SET="$CLAUDE_PROFILES_SET" run_found_script "35-claude-profiles.sh" || exit 1
elif [ "$CLAUDE_BACKUP_CLEAN_ONLY" = true ]; then
    echo "🧹 Installing claude-backup-clean to ~/.local/bin..."
    run_found_script "36-claude-backup-clean.sh" || exit 1
elif [ -n "$SCRIPT_ONLY" ]; then
    echo "📜 Running single script: $SCRIPT_ONLY (profile: $PROFILE)"
    # Allow only script basename (no path traversal)
    case "$SCRIPT_ONLY" in
        */*) echo "❌ Invalid script name (no path allowed): $SCRIPT_ONLY"; exit 1 ;;
    esac
    run_found_script "$SCRIPT_ONLY" || exit 1
else
    # Execute the run-scripts.sh based on profile
    echo "🔧 Running installation scripts (profile: $PROFILE)..."

    case "$PROFILE" in
        classic)
            if [ -f "./scripts/classic/run-scripts.sh" ]; then
                bash ./scripts/classic/run-scripts.sh
            else
                echo "❌ Classic profile scripts not found"
                exit 1
            fi
            ;;
        minimal)
            if [ -f "./scripts/minimal/run-scripts.sh" ]; then
                bash ./scripts/minimal/run-scripts.sh
            else
                echo "❌ Minimal profile scripts not found"
                exit 1
            fi
            ;;
    esac
fi

echo "✅ Installation completed!"
