#!/bin/bash


RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' 


CONFIG_FILE="$HOME/.git-toolkit-config"
GIT_CONFIG="$HOME/.gitconfig"


show_header() {
    clear
    echo -e "${PURPLE}╔══════════════════════════════════════════════════════╗${NC}"
    echo -e "${PURPLE}║               Git 工具箱 - 多功能版本                ║${NC}"
    echo -e "${PURPLE}╚══════════════════════════════════════════════════════╝${NC}"
    echo ""
}


load_config() {
    if [ -f "$CONFIG_FILE" ]; then
        source "$CONFIG_FILE"
    else
        GIT_USER=""
        GIT_EMAIL=""
        GIT_TOKEN=""
        DEFAULT_REPO=""
    fi
}


save_config() {
    cat > "$CONFIG_FILE" << EOF
GIT_USER="$GIT_USER"
GIT_EMAIL="$GIT_EMAIL"
GIT_TOKEN="$GIT_TOKEN"
DEFAULT_REPO="$DEFAULT_REPO"
EOF
    chmod 600 "$CONFIG_FILE"
}


check_git() {
    if ! command -v git &> /dev/null; then
        echo -e "${RED}❌ 未安装 Git，请先安装 Git${NC}"
        exit 1
    fi
}


show_menu() {
    echo -e "${CYAN}请选择操作模式：${NC}"
    echo -e "${YELLOW}1. 快速上传文件到现有仓库${NC}"
    echo -e "${YELLOW}2. 清空仓库后上传（删除历史）${NC}"
    echo -e "${YELLOW}3. 创建并上传到新仓库${NC}"
    echo -e "${YELLOW}4. 删除远程仓库（谨慎！）${NC}"
    echo -e "${YELLOW}5. 配置 Git 账号信息${NC}"
    echo -e "${YELLOW}6. 设置 SSH 密钥${NC}"
    echo -e "${YELLOW}7. 修复常见 Git 问题${NC}"
    echo -e "${YELLOW}8. 查看仓库状态${NC}"
    echo -e "${YELLOW}0. 退出${NC}"
    echo ""
}


quick_upload() {
    echo -e "${GREEN}🚀 模式1：快速上传文件到现有仓库${NC}"
    echo ""
    
    read -p "请输入仓库路径（直接回车使用当前目录）: " repo_path
    repo_path=${repo_path:-$(pwd)}
    
    if [ ! -d "$repo_path" ]; then
        echo -e "${RED}❌ 路径不存在${NC}"
        return
    fi
    
    cd "$repo_path" || return
    
    if [ ! -d ".git" ]; then
        echo -e "${RED}❌ 这不是 Git 仓库${NC}"
        read -p "是否初始化为新仓库？(y/N): " init_repo
        if [[ $init_repo =~ ^[Yy]$ ]]; then
            read -p "请输入远程仓库URL（如 https://github.com/用户名/仓库名）: " remote_url
            git init
            git add .
            git commit -m "初始提交"
            git branch -M main
            git remote add origin "$remote_url"
        else
            return
        fi
    fi
    
    echo ""
    echo -e "${YELLOW}📊 当前状态：${NC}"
    git status
    
    read -p "是否添加所有文件？(y/N): " add_all
    if [[ $add_all =~ ^[Yy]$ ]]; then
        git add .
    else
        echo "请手动输入要添加的文件（空格分隔，支持通配符）:"
        read -a files
        git add "${files[@]}"
    fi
    
    read -p "提交信息: " commit_msg
    commit_msg=${commit_msg:-"更新于 $(date '+%Y-%m-%d %H:%M:%S')"}
    
    git commit -m "$commit_msg"
    
    echo ""
    echo -e "${YELLOW}🌐 推送选项：${NC}"
    echo "1. 正常推送 (git push)"
    echo "2. 强制推送 (git push --force)"
    echo "3. 仅提交，不推送"
    
    read -p "选择推送方式 (1/2/3): " push_choice
    
    case $push_choice in
        1)
            git push origin main
            ;;
        2)
            echo -e "${RED}⚠️  强制推送会覆盖远程历史！${NC}"
            read -p "确认强制推送？(y/N): " confirm_force
            if [[ $confirm_force =~ ^[Yy]$ ]]; then
                git push -f origin main
            fi
            ;;
        3)
            echo "✅ 已提交，未推送"
            ;;
        *)
            git push origin main
            ;;
    esac
    
    echo -e "${GREEN}✅ 上传完成！${NC}"
}

# 功能2：清空仓库后上传
clean_and_upload() {
    echo -e "${GREEN}🗑️  模式2：清空仓库后上传${NC}"
    echo -e "${RED}⚠️  警告：这将删除所有提交历史！${NC}"
    echo ""
    
    read -p "请输入仓库路径: " repo_path
    repo_path=${repo_path:-$(pwd)}
    
    cd "$repo_path" || return
    
    if [ ! -d ".git" ]; then
        echo -e "${RED}❌ 这不是 Git 仓库${NC}"
        return
    fi
    
    # 备份当前分支名
    current_branch=$(git branch --show-current)
    
    echo ""
    echo "📊 当前仓库信息："
    echo "   分支: $current_branch"
    echo "   提交数: $(git rev-list --count HEAD)"
    echo "   文件数: $(git ls-files | wc -l)"
    
    read -p "是否创建备份分支？(y/N): " backup_choice
    if [[ $backup_choice =~ ^[Yy]$ ]]; then
        backup_name="backup-$(date +%Y%m%d-%H%M%S)"
        git branch "$backup_name"
        echo -e "${GREEN}✅ 已创建备份分支: $backup_name${NC}"
    fi
    
    echo -e "${RED}🔴 确认清空仓库所有历史？(输入 'DELETE' 确认): ${NC}"
    read confirm
    
    if [ "$confirm" != "DELETE" ]; then
        echo "操作取消"
        return
    fi
    
    # 执行清空
    git checkout --orphan new-start
    git add -A
    git commit -m "仓库重置于 $(date '+%Y-%m-%d %H:%M:%S')"
    git branch -D "$current_branch"
    git branch -M "$current_branch"
    
    read -p "是否推送到远程？(y/N): " push_choice
    if [[ $push_choice =~ ^[Yy]$ ]]; then
        git push -f origin "$current_branch"
        echo -e "${GREEN}✅ 已强制推送到远程${NC}"
    fi
    
    echo -e "${GREEN}✅ 仓库已清空并上传当前文件${NC}"
}

# 功能3：创建并上传到新仓库
create_new_repo() {
    echo -e "${GREEN}🆕 模式3：创建并上传到新仓库${NC}"
    echo ""
    
    read -p "项目本地路径: " project_path
    project_path=${project_path:-$(pwd)}
    
    if [ ! -d "$project_path" ]; then
        read -p "路径不存在，是否创建？(y/N): " create_dir
        if [[ $create_dir =~ ^[Yy]$ ]]; then
            mkdir -p "$project_path"
            cd "$project_path" || return
        else
            return
        fi
    fi
    
    cd "$project_path" || return
    
    # 如果已经是git仓库，询问处理方式
    if [ -d ".git" ]; then
        echo -e "${YELLOW}⚠️  当前目录已是 Git 仓库${NC}"
        echo "1. 使用现有仓库"
        echo "2. 删除.git重新开始"
        echo "3. 取消"
        
        read -p "选择 (1/2/3): " choice
        case $choice in
            2)
                rm -rf .git
                ;;
            3)
                return
                ;;
        esac
    fi
    
    echo ""
    echo "📁 当前目录文件："
    ls -la
    
    read -p "远程仓库URL（GitHub/GitLab等）: " remote_url
    
    if [ -z "$remote_url" ]; then
        echo -e "${RED}❌ 需要远程仓库URL${NC}"
        return
    fi
    
    # 初始化
    git init
    git add .
    git commit -m "初始提交"
    git branch -M main
    git remote add origin "$remote_url"
    
    echo ""
    echo "🌐 推送选项："
    echo "1. 正常推送 (可能需要账号密码)"
    echo "2. 使用 SSH (如果配置了SSH密钥)"
    
    read -p "选择推送方式 (1/2): " push_method
    
    case $push_method in
        1)
            git push -u origin main
            ;;
        2)
            # 转换为SSH格式
            if [[ $remote_url == https://* ]]; then
                ssh_url=$(echo "$remote_url" | sed 's|https://|git@|' | sed 's|/|:|')
                git remote set-url origin "$ssh_url"
            fi
            git push -u origin main
            ;;
    esac
    
    echo -e "${GREEN}✅ 新仓库创建并上传成功！${NC}"
    echo "🔗 远程地址: $remote_url"
}

# 功能4：配置 Git 账号
setup_git_account() {
    echo -e "${GREEN}👤 模式5：配置 Git 账号信息${NC}"
    echo ""
    
    if [ -z "$GIT_USER" ]; then
        read -p "GitHub 用户名: " git_user
        GIT_USER="$git_user"
    else
        read -p "GitHub 用户名 [当前: $GIT_USER]: " git_user
        GIT_USER=${git_user:-$GIT_USER}
    fi
    
    if [ -z "$GIT_EMAIL" ]; then
        read -p "GitHub 邮箱: " git_email
        GIT_EMAIL="$git_email"
    else
        read -p "GitHub 邮箱 [当前: $GIT_EMAIL]: " git_email
        GIT_EMAIL=${git_email:-$GIT_EMAIL}
    fi
    
    read -p "GitHub 访问令牌（输入跳过保存）: " git_token
    if [ -n "$git_token" ]; then
        GIT_TOKEN="$git_token"
    fi
    
    # 设置全局配置
    git config --global user.name "$GIT_USER"
    git config --global user.email "$GIT_EMAIL"
    
    # 保存到脚本配置
    save_config
    
    echo ""
    echo -e "${GREEN}✅ Git 账号配置完成${NC}"
    echo "   用户名: $GIT_USER"
    echo "   邮箱: $GIT_EMAIL"
    
    # 设置凭证存储
    echo ""
    echo "🔑 凭证存储设置："
    echo "1. 缓存（默认15分钟）"
    echo "2. 存储（永久，不太安全）"
    echo "3. 不设置"
    
    read -p "选择 (1/2/3): " cred_choice
    
    case $cred_choice in
        1)
            git config --global credential.helper cache
            read -p "缓存时间（秒，默认900）: " cache_time
            cache_time=${cache_time:-900}
            git config --global credential.helper "cache --timeout=$cache_time"
            echo "✅ 已设置缓存: ${cache_time}秒"
            ;;
        2)
            git config --global credential.helper store
            echo "✅ 已设置永久存储（注意安全）"
            ;;
    esac
}

# 功能5：修复常见问题
fix_common_issues() {
    echo -e "${GREEN}🔧 模式7：修复常见 Git 问题${NC}"
    echo ""
    
    echo "请选择要修复的问题："
    echo "1. 权限问题 (chmod +x)"
    echo "2. 大文件推送失败"
    echo "3. SSL 证书问题"
    echo "4. 行尾换行符问题"
    echo "5. 仓库太大推送失败"
    echo "6. 所有问题"
    
    read -p "选择 (1-6): " fix_choice
    
    case $fix_choice in
        1)
            echo "🔧 修复文件权限..."
            find . -name "*.sh" -exec chmod +x {} \;
            find . -name "gradlew" -exec chmod +x {} \;
            echo "✅ 执行权限已修复"
            ;;
        2)
            echo "🔧 设置大文件缓冲区..."
            git config --global http.postBuffer 524288000
            git config --global pack.windowMemory 512m
            git config --global pack.packSizeLimit 512m
            echo "✅ 大文件缓冲区已设置"
            ;;
        3)
            echo "🔧 修复 SSL 问题..."
            git config --global http.sslVerify false
            echo "⚠️  已关闭 SSL 验证（临时方案）"
            ;;
        4)
            echo "🔧 修复行尾换行符..."
            git config --global core.autocrlf false
            echo "✅ 行尾设置完成"
            ;;
        5)
            echo "🔧 优化大仓库推送..."
            git config --global pack.window 0
            git config --global pack.depth 0
            git config --global pack.threads 1
            echo "✅ 大仓库优化完成"
            ;;
        6)
            echo "🔧 修复所有常见问题..."
            # 执行所有修复
            find . -name "*.sh" -exec chmod +x {} \;
            find . -name "gradlew" -exec chmod +x {} \;
            git config --global http.postBuffer 524288000
            git config --global pack.windowMemory 512m
            git config --global core.autocrlf false
            git config --global pack.window 0
            echo "✅ 所有常见问题已修复"
            ;;
    esac
}

# 主函数
main() {
    check_git
    load_config
    
    while true; do
        show_header
        show_menu
        
        read -p "请选择操作 (0-8): " choice
        
        case $choice in
            1)
                quick_upload
                ;;
            2)
                clean_and_upload
                ;;
            3)
                create_new_repo
                ;;
            4)
                echo -e "${RED}⚠️  删除仓库功能需谨慎使用${NC}"
                echo "此功能建议直接在 GitHub 网页操作"
                echo "访问: https://github.com/3602308846/mcnewdeath/settings"
                ;;
            5)
                setup_git_account
                ;;
            6)
                echo -e "${YELLOW}📝 SSH 密钥设置指南：${NC}"
                echo "1. 生成密钥: ssh-keygen -t ed25519 -C \"邮箱\""
                echo "2. 查看公钥: cat ~/.ssh/id_ed25519.pub"
                echo "3. 添加到 GitHub: https://github.com/settings/keys"
                echo "4. 测试连接: ssh -T git@github.com"
                ;;
            7)
                fix_common_issues
                ;;
            8)
                echo -e "${CYAN}📊 仓库状态：${NC}"
                git status
                git log --oneline -5
                ;;
            0)
                echo -e "${GREEN}👋 退出 Git 工具箱${NC}"
                exit 0
                ;;
            *)
                echo -e "${RED}❌ 无效选择${NC}"
                ;;
        esac
        
        echo ""
        read -p "按回车键继续..." dummy
    done
}

# 运行主函数
main