#!/bin/bash
# Gitea小说项目管理脚本
# 用于管理同步到Gitea的小说项目

PROJECTS_DIR="/root/.openclaw/workspace/projects"
GITEA_BASE="https://gitea.nevadalice.top:226/liyuchen"

# 项目映射
declare -A PROJECT_MAP=(
    ["末日重生_囤货"]="novel-doomsday-resurgence"
    ["杀了婆婆的我"]="novel-killed-mother-in-law"
    ["挑战者"]="novel-challenger"
    ["小说工具"]="novel-tools"
)

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"
}

show_status() {
    echo "📊 Gitea小说项目状态"
    echo "======================"
    echo ""
    
    for local_dir in "${!PROJECT_MAP[@]}"; do
        repo_name="${PROJECT_MAP[$local_dir]}"
        project_path="$PROJECTS_DIR/$local_dir"
        
        echo "📖 $(echo $local_dir | sed 's/_/ /g')"
        echo "   ├─ 本地目录: $project_path"
        echo "   ├─ Gitea仓库: $repo_name"
        echo "   ├─ 访问地址: $GITEA_BASE/$repo_name"
        
        if [ -d "$project_path" ]; then
            cd "$project_path"
            
            # 本地状态
            chapter_count=$(find . -name "*.md" | wc -l)
            last_commit=$(git log -1 --format="%ad" --date=short 2>/dev/null || echo "无")
            
            # 远程状态
            remote_url=$(git remote get-url origin 2>/dev/null || echo "未配置")
            
            echo "   ├─ 本地章节: $chapter_count 个"
            echo "   ├─ 最后提交: $last_commit"
            echo "   └─ 远程仓库: $(echo $remote_url | sed 's|https://gitea.nevadalice.top:226/liyuchen/||')"
        else
            echo "   ├─ 状态: ❌ 本地目录不存在"
        fi
        
        echo ""
    done
}

sync_project() {
    local_dir="$1"
    
    if [ -z "$local_dir" ]; then
        echo "请指定要同步的项目目录名："
        echo "可用项目: ${!PROJECT_MAP[@]}"
        read local_dir
    fi
    
    repo_name="${PROJECT_MAP[$local_dir]}"
    
    if [ -z "$repo_name" ]; then
        echo "❌ 未知项目: $local_dir"
        echo "可用项目: ${!PROJECT_MAP[@]}"
        return 1
    fi
    
    project_path="$PROJECTS_DIR/$local_dir"
    
    if [ ! -d "$project_path" ]; then
        echo "❌ 本地目录不存在: $project_path"
        return 1
    fi
    
    echo "🔄 同步项目: $local_dir -> $repo_name"
    echo "   本地路径: $project_path"
    echo "   远程仓库: $GITEA_BASE/$repo_name"
    echo ""
    
    cd "$project_path"
    
    # 检查是否有未提交的更改
    if [ -n "$(git status --porcelain)" ]; then
        echo "📝 检测到未提交的更改:"
        git status --short
        echo ""
        echo "是否提交这些更改？ (y/n)"
        read confirm
        
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            echo "请输入提交信息:"
            read commit_msg
            if [ -z "$commit_msg" ]; then
                commit_msg="更新 $(date '+%Y-%m-%d %H:%M:%S')"
            fi
            
            git add .
            git commit -m "$commit_msg"
            echo "✅ 更改已提交"
        else
            echo "⚠️  跳过提交，直接推送现有提交"
        fi
    fi
    
    # 配置远程仓库
    if ! git remote get-url origin >/dev/null 2>&1; then
        echo "🔧 配置远程仓库..."
        git remote add origin "$GITEA_BASE/$repo_name.git"
    fi
    
    # 推送到Gitea
    echo "🚀 推送到Gitea..."
    if git push -u origin master 2>&1 | grep -E "(error|fatal)"; then
        echo "⚠️  推送失败，尝试强制推送..."
        if git push -u origin master --force 2>&1 | grep -E "(error|fatal)"; then
            echo "❌ 推送失败，请检查网络或权限"
            return 1
        else
            echo "✅ 强制推送成功！"
        fi
    else
        echo "✅ 推送成功！"
    fi
    
    echo ""
    echo "🌐 仓库地址: $GITEA_BASE/$repo_name"
    log "同步项目: $local_dir -> $repo_name"
}

sync_all() {
    echo "🔄 同步所有项目到Gitea"
    echo "======================"
    echo ""
    
    for local_dir in "${!PROJECT_MAP[@]}"; do
        echo "📦 同步: $local_dir"
        sync_project "$local_dir"
        echo ""
    done
    
    echo "✅ 所有项目同步完成！"
}

clone_project() {
    repo_name="$1"
    
    if [ -z "$repo_name" ]; then
        echo "请指定要克隆的仓库名："
        echo "可用仓库: ${PROJECT_MAP[@]}"
        read repo_name
    fi
    
    # 检查是否是对应的仓库名
    local_dir=""
    for key in "${!PROJECT_MAP[@]}"; do
        if [ "${PROJECT_MAP[$key]}" = "$repo_name" ]; then
            local_dir="$key"
            break
        fi
    done
    
    if [ -z "$local_dir" ]; then
        echo "❌ 未知仓库: $repo_name"
        echo "可用仓库: ${PROJECT_MAP[@]}"
        return 1
    fi
    
    project_path="$PROJECTS_DIR/$local_dir"
    
    if [ -d "$project_path" ]; then
        echo "⚠️  本地目录已存在: $project_path"
        echo "是否重新克隆？ (y/n)"
        read confirm
        
        if [ "$confirm" != "y" ] && [ "$confirm" != "Y" ]; then
            echo "取消克隆"
            return 0
        fi
        
        # 备份现有目录
        backup_dir="${project_path}_backup_$(date '+%Y%m%d_%H%M%S')"
        mv "$project_path" "$backup_dir"
        echo "📦 原目录已备份到: $backup_dir"
    fi
    
    echo "⬇️  克隆仓库: $repo_name"
    echo "   到目录: $project_path"
    echo ""
    
    git clone "$GITEA_BASE/$repo_name.git" "$project_path"
    
    if [ $? -eq 0 ]; then
        echo "✅ 克隆成功！"
        echo "   本地路径: $project_path"
        log "克隆仓库: $repo_name -> $project_path"
    else
        echo "❌ 克隆失败"
        # 恢复备份
        if [ -d "$backup_dir" ]; then
            mv "$backup_dir" "$project_path"
            echo "已恢复原目录"
        fi
    fi
}

open_gitea() {
    echo "🌐 打开Gitea页面..."
    echo ""
    echo "首页: $GITEA_BASE"
    echo ""
    
    for repo_name in "${PROJECT_MAP[@]}"; do
        echo "📖 $repo_name: $GITEA_BASE/$repo_name"
    done
    
    echo ""
    echo "请使用浏览器访问以上链接"
}

show_help() {
    echo "Gitea小说项目管理脚本"
    echo "======================"
    echo ""
    echo "用法: $0 [命令]"
    echo ""
    echo "命令:"
    echo "  status     显示所有项目状态"
    echo "  sync [项目] 同步指定项目到Gitea"
    echo "  sync-all   同步所有项目到Gitea"
    echo "  clone [仓库] 从Gitea克隆仓库到本地"
    echo "  open       打开Gitea页面链接"
    echo "  help       显示帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 status              # 查看所有项目状态"
    echo "  $0 sync 末日重生_囤货    # 同步《末日重生》项目"
    echo "  $0 sync-all            # 同步所有项目"
    echo "  $0 clone novel-tools   # 克隆工具集仓库"
    echo ""
    echo "可用项目:"
    for local_dir in "${!PROJECT_MAP[@]}"; do
        echo "  - $local_dir (Gitea: ${PROJECT_MAP[$local_dir]})"
    done
}

# 主程序
case "$1" in
    "status")
        show_status
        ;;
    "sync")
        sync_project "$2"
        ;;
    "sync-all")
        sync_all
        ;;
    "clone")
        clone_project "$2"
        ;;
    "open")
        open_gitea
        ;;
    "help"|"--help"|"-h"|"")
        show_help
        ;;
    *)
        echo "❌ 未知命令: $1"
        echo ""
        show_help
        ;;
esac