#!/bin/bash
# GitLink CLI 一键卸载脚本
# 删除二进制、skills和配置文件
# 用法: curl -sSL https://www.gitlink.org.cn/Gitlink/gitlink-cli/raw/master/uninstall.sh | bash
# 或者: bash uninstall.sh [--purge]

set -e

REPO_OWNER="Gitlink"
REPO_NAME="gitlink-cli"
BINARY_NAME="gitlink-cli"
API_BASE="https://www.gitlink.org.cn"

# 默认安装目录（按优先级排序）
POSSIBLE_INSTALL_DIRS=(
    "/usr/local/bin"
    "/usr/bin"
    "$HOME/.local/bin"
    "$HOME/bin"
    "/opt/homebrew/bin"
    "$HOME/.gitlink-cli/bin"
)

# ---------- 颜色输出 ----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BLUE='\033[0;34m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC}  $*"; }
warn()  { echo -e "${YELLOW}[WARN]${NC}  $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*"; }
step()  { echo -e "${CYAN}[STEP]${NC} $*"; }
ask()  { echo -e "${BLUE}[ASK]${NC}  $*"; }

# ---------- 查找二进制文件 ----------
find_binary() {
    step "查找 ${BINARY_NAME} 二进制文件..."

    for dir in "${POSSIBLE_INSTALL_DIRS[@]}"; do
        if [ -f "${dir}/${BINARY_NAME}" ]; then
            INSTALL_DIR="${dir}"
            info "找到安装目录: ${INSTALL_DIR}"
            return 0
        fi
    done

    # 检查是否在PATH中
    if command -v "${BINARY_NAME}" >/dev/null 2>&1; then
        INSTALL_DIR="$(dirname "$(command -v "${BINARY_NAME}")")"
        info "通过PATH找到安装目录: ${INSTALL_DIR}"
        return 0
    fi

    warn "未找到 ${BINARY_NAME} 二进制文件"
    return 1
}

# ---------- 检查安装状态 ----------
check_installation_status() {
    local found_items=()

    step "检查安装状态..."

    # 检查二进制
    if [ -n "${INSTALL_DIR}" ] && [ -f "${INSTALL_DIR}/${BINARY_NAME}" ]; then
        found_items+=("二进制文件: ${INSTALL_DIR}/${BINARY_NAME}")
    fi

    # 检查skills
    if [ -d "${HOME}/.gitlink/skills" ]; then
        found_items+=("Skills: ${HOME}/.gitlink/skills")
    fi

    # 检查配置
    if [ -d "${HOME}/.config/gitlink-cli" ]; then
        found_items+=("配置: ${HOME}/.config/gitlink-cli")
    fi

    if [ -d "${HOME}/.gitlink" ]; then
        found_items+=("GitLink数据: ${HOME}/.gitlink")
    fi

    # 检查npm安装
    if npm list -g "@gitlink-ai/cli" >/dev/null 2>&1; then
        found_items+=("npm包: @gitlink-ai/cli (全局)")
    fi

    if [ ${#found_items[@]} -eq 0 ]; then
        warn "未检测到 ${BINARY_NAME} 安装"
        return 1
    fi

    info "检测到以下组件:"
    for item in "${found_items[@]}"; do
        echo "  - ${item}"
    done

    return 0
}

# ---------- 删除二进制 ----------
remove_binary() {
    if [ -z "${INSTALL_DIR}" ]; then
        warn "跳过二进制删除（未找到安装目录）"
        return 0
    fi

    step "删除二进制文件..."
    local binary_path="${INSTALL_DIR}/${BINARY_NAME}"

    if [ ! -f "${binary_path}" ]; then
        warn "二进制文件不存在: ${binary_path}"
        return 0
    fi

    # 尝试删除
    if [ -w "${binary_path}" ]; then
        rm -f "${binary_path}"
        info "已删除: ${binary_path}"
    else
        if [ -w "${INSTALL_DIR}" ]; then
            rm -f "${binary_path}"
            info "已删除: ${binary_path}"
        else
            # 需要sudo权限
            warn "需要管理员权限删除二进制文件"
            if sudo rm -f "${binary_path}" 2>/dev/null; then
                info "已删除: ${binary_path}"
            else
                error "删除失败，请手动删除: ${binary_path}"
                return 1
            fi
        fi
    fi
}

# ---------- 删除Skills ----------
remove_skills() {
    step "删除 Skills..."

    if [ ! -d "${HOME}/.gitlink/skills" ]; then
        warn "Skills目录不存在: ${HOME}/.gitlink/skills"
        return 0
    fi

    # 显示Skills信息
    local skill_count=$(find "${HOME}/.gitlink/skills" -maxdepth 1 -type d | wc -l)
    info "找到 ${skill_count} 个Skills"

    # 删除
    rm -rf "${HOME}/.gitlink/skills"
    info "已删除Skills"
}

# ---------- 删除配置 ----------
remove_config() {
    if [ "$PURGE_ALL" != "true" ]; then
        ask "是否删除配置文件和数据? [y/N] "
        read -r response
        if [[ ! "$response" =~ ^[Yy]$ ]]; then
            info "保留配置文件"
            return 0
        fi
    fi

    step "删除配置文件..."

    local config_dirs=(
        "$HOME/.config/gitlink-cli"
        "$HOME/.gitlink"
    )

    for dir in "${config_dirs[@]}"; do
        if [ -d "$dir" ]; then
            info "删除: $dir"
            rm -rf "$dir"
        fi
    done

    info "配置文件已删除"
}

# ---------- 卸载npm包 ----------
uninstall_npm() {
    if ! npm list -g "@gitlink-ai/cli" >/dev/null 2>&1; then
        return 0
    fi

    step "卸载npm包..."

    ask "检测到npm全局安装的 ${BINARY_NAME}，是否卸载? [y/N] "
    read -r response

    if [[ "$response" =~ ^[Yy]$ ]]; then
        if npm uninstall -g "@gitlink-ai/cli" 2>/dev/null; then
            info "npm包已卸载"
        else
            warn "npm包卸载失败，请手动执行: npm uninstall -g @gitlink-ai/cli"
        fi
    else
        info "保留npm包"
    fi
}

# ---------- 显示卸载摘要 ----------
show_summary() {
    echo ""
    echo "========================================"
    info "卸载完成！"
    echo "========================================"
    echo ""

    if [ "$PURGE_ALL" = "true" ]; then
        warn "已完全删除所有文件（包括配置）"
    else
        info "以下文件可能需要手动清理:"
        echo "  - ${HOME}/.config/gitlink-cli"
        echo "  - ${HOME}/.gitlink"
        echo ""
        info "如需删除，请重新运行: bash uninstall.sh --purge"
    fi

    echo ""
    info "感谢使用 GitLink CLI！"
    echo "如有任何问题，请访问: https://www.gitlink.org.cn/Gitlink/gitlink-cli/issues"
    echo ""
}

# ---------- 确认卸载 ----------
confirm_uninstall() {
    if [ "$AUTO_CONFIRM" = "true" ]; then
        return 0
    fi

    echo ""
    warn "即将卸载 ${BINARY_NAME} 及相关文件"
    ask "确认继续? [y/N] "
    read -r response

    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        info "取消卸载"
        exit 0
    fi
}

# ---------- 主流程 ----------
main() {
    # 解析参数
    PURGE_ALL="false"
    AUTO_CONFIRM="false"

    while [[ $# -gt 0 ]]; do
        case $1 in
            --purge)
                PURGE_ALL="true"
                shift
                ;;
            --yes|-y)
                AUTO_CONFIRM="true"
                shift
                ;;
            --help|-h)
                echo "用法: bash uninstall.sh [选项]"
                echo ""
                echo "选项:"
                echo "  --purge    删除所有文件（包括配置）"
                echo "  --yes, -y  自动确认，不询问"
                echo "  --help, -h 显示此帮助"
                echo ""
                echo "示例:"
                echo "  bash uninstall.sh           # 交互式卸载"
                echo "  bash uninstall.sh --purge   # 完全删除"
                echo "  bash uninstall.sh -y        # 自动确认"
                exit 0
                ;;
            *)
                error "未知选项: $1"
                echo "使用 --help 查看帮助"
                exit 1
                ;;
        esac
    done

    # 欢迎信息
    echo ""
    echo "========================================"
    echo "  GitLink CLI 一键卸载"
    echo "========================================"
    echo ""

    # 查找二进制
    find_binary

    # 检查安装状态
    if ! check_installation_status; then
        error "未检测到 ${BINARY_NAME} 安装"
        exit 1
    fi

    # 确认卸载
    confirm_uninstall

    # 执行卸载
    remove_binary
    remove_skills
    remove_config
    uninstall_npm

    # 显示摘要
    show_summary
}

# 运行主流程
main "$@"