#!/bin/bash
set -euo pipefail

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

success() {
    echo -e "${BLUE}[DONE]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
    exit 1
}

section() {
    echo
    echo -e "${BOLD}${BLUE}== $1 ==${NC}"
}

usage() {
    cat <<'EOF'
用法:
  bash install.sh                # 交互式选择安装项
  bash install.sh all            # 安装全部工具
  bash install.sh docker         # 仅安装 Docker
  bash install.sh nvm            # 仅安装 NVM
  bash install.sh mambaconda     # 仅安装 Mambaconda
  bash install.sh docker nvm     # 安装多个指定工具
  bash install.sh --help
EOF
}

run_script() {
    local script_name="$1"
    local script_path="$SCRIPT_DIR/$script_name"

    if [[ ! -f "$script_path" ]]; then
        error "未找到脚本: $script_path"
    fi

    section "执行 $script_name"
    bash "$script_path"
}

install_docker() {
    run_script "install-docker.sh"
}

install_nvm() {
    run_script "install-nvm.sh"
}

install_mambaconda() {
    run_script "install-mambaconda.sh"
}

install_targets() {
    local target

    for target in "$@"; do
        case "$target" in
            docker) install_docker ;;
            nvm) install_nvm ;;
            mambaconda) install_mambaconda ;;
            all)
                install_docker
                install_nvm
                install_mambaconda
                ;;
            *)
                error "未知安装目标: $target"
                ;;
        esac
    done
}

interactive_install() {
    local reply=""
    local selected=()

    section "交互式安装"

    read -r -p "是否安装 Docker? [y/N]: " reply
    if [[ "$reply" =~ ^[Yy]$ ]]; then
        selected+=("docker")
    fi

    read -r -p "是否安装 NVM? [y/N]: " reply
    if [[ "$reply" =~ ^[Yy]$ ]]; then
        selected+=("nvm")
    fi

    read -r -p "是否安装 Mambaconda? [y/N]: " reply
    if [[ "$reply" =~ ^[Yy]$ ]]; then
        selected+=("mambaconda")
    fi

    if [[ ${#selected[@]} -eq 0 ]]; then
        warn "未选择任何安装项。"
        return
    fi

    install_targets "${selected[@]}"
    success "所选安装项已执行完成。"
}

main() {
    section "环境安装入口"

    if [[ $# -eq 0 ]]; then
        interactive_install
        return
    fi

    case "${1:-}" in
        -h|--help)
            usage
            return
            ;;
    esac

    install_targets "$@"
    success "安装流程执行完成。"
}

main "$@"
