#!/bin/bash
# 简单小说管理器 - 本地独立项目管理

PROJECTS_DIR="/root/.openclaw/workspace/projects"
LOGFILE="/root/.openclaw/workspace/novel_manager.log"

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

show_menu() {
    echo "========== 小说项目管理器 =========="
    echo "1. 查看所有项目"
    echo "2. 查看项目详情"
    echo "3. 创建新项目"
    echo "4. 统计项目字数"
    echo "5. 导出项目备份"
    echo "6. 显示更新日志"
    echo "7. 退出"
    echo "=================================="
}

list_projects() {
    echo "📚 当前项目列表："
    echo ""
    
    for project_dir in "$PROJECTS_DIR"/*; do
        if [ -d "$project_dir" ]; then
            project_name=$(basename "$project_dir")
            
            # 读取项目信息
            if [ -f "$project_dir/PROJECT.md" ]; then
                title=$(grep "书名" "$project_dir/PROJECT.md" | head -1 | cut -d':' -f2 | tr -d ' ' || echo "未知")
            else
                title="未知"
            fi
            
            # 统计章节
            chapter_count=$(find "$project_dir/chapters" -name "*.md" 2>/dev/null | wc -l)
            
            # 统计字数
            if [ $chapter_count -gt 0 ]; then
                total_words=0
                for chapter in "$project_dir/chapters"/*.md 2>/dev/null; do
                    if [ -f "$chapter" ]; then
                        words=$(wc -w < "$chapter" 2>/dev/null || echo 0)
                        total_words=$((total_words + words))
                    fi
                done
            else
                total_words=0
            fi
            
            echo "  📖 $project_name"
            echo "    书名: $title"
            echo "    章节: $chapter_count 章"
            echo "    字数: $total_words 字"
            echo ""
        fi
    done
}

show_project_detail() {
    echo "请输入项目名称："
    read project_name
    
    project_path="$PROJECTS_DIR/$project_name"
    
    if [ ! -d "$project_path" ]; then
        echo "❌ 项目不存在: $project_name"
        return 1
    fi
    
    echo ""
    echo "📋 项目详情: $project_name"
    echo "----------------------------------------"
    
    # 显示项目信息
    if [ -f "$project_path/PROJECT.md" ]; then
        echo "项目信息："
        grep -E "(书名|类型|状态|章节)" "$project_path/PROJECT.md" | head -6
    fi
    
    echo ""
    echo "文件结构："
    find "$project_path" -type f -name "*.md" | sed "s|$project_path/|  |" | sort
    
    echo ""
    echo "章节列表："
    find "$project_path/chapters" -name "*.md" 2>/dev/null | sort | while read chapter; do
        ch_name=$(basename "$chapter" .md)
        words=$(wc -w < "$chapter" 2>/dev/null || echo 0)
        echo "  📄 $ch_name ($words 字)"
    done
}

create_new_project() {
    echo "创建新小说项目"
    echo "---------------"
    
    echo "请输入项目目录名（英文或拼音）："
    read dir_name
    
    echo "请输入小说标题："
    read novel_title
    
    echo "请输入小说类型（如：玄幻、悬疑、末世）："
    read novel_type
    
    project_path="$PROJECTS_DIR/$dir_name"
    
    if [ -d "$project_path" ]; then
        echo "❌ 项目已存在: $dir_name"
        return 1
    fi
    
    # 创建项目结构
    mkdir -p "$project_path"
    mkdir -p "$project_path/chapters"
    mkdir -p "$project_path/outlines"
    mkdir -p "$project_path/assets/characters"
    mkdir -p "$project_path/progress"
    
    # 创建项目说明
    cat > "$project_path/PROJECT.md" << PROJECT_EOF
# 《${novel_title}》项目

## 项目信息
- **书名**: ${novel_title}
- **类型**: ${novel_type}
- **状态**: 新项目
- **目标平台**: 番茄小说
- **作者**: 唐天洛
- **创建时间**: $(date '+%Y年%m月%d日')

## 项目结构
\`\`\`
${dir_name}/
├── PROJECT.md              # 项目说明
├── chapters/               # 章节文件
├── outlines/               # 大纲和规划
├── assets/characters/      # 人物设定
└── progress/               # 进度跟踪
\`\`\`

## 当前进度
- **章节**: 0章
- **字数**: 0字
- **状态**: 规划阶段

## 创作计划
1. **第一阶段**: 人物设定和世界观构建
2. **第二阶段**: 大纲规划和爽点设计
3. **第三阶段**: 黄金三章创作
4. **第四阶段**: 持续更新
PROJECT_EOF
    
    # 创建README
    cat > "$project_path/README.md" << README_EOF
# 《${novel_title}》

## 项目简介
${novel_type}题材小说，${novel_title}

## 快速开始
1. 在 \`outlines/\` 目录下规划大纲
2. 在 \`assets/characters/\` 目录下创建人物设定
3. 在 \`chapters/\` 目录下创作章节

## 更新日志
- $(date '+%Y-%m-%d'): 项目创建
README_EOF
    
    # 初始化Git
    cd "$project_path"
    git init
    git config user.name "唐天洛"
    git config user.email "563415956@qq.com"
    
    # 创建.gitignore
    cat > .gitignore << GITIGNORE_EOF
# 临时文件
*.tmp
*.log
*.bak

# 系统文件
.DS_Store
Thumbs.db

# 编辑器文件
.vscode/
.idea/
*.swp

# 配置文件
config.json
*.key
.env
GITIGNORE_EOF
    
    # 提交
    git add .
    git commit -m "项目初始化: ${novel_title}"
    
    echo ""
    echo "✅ 项目创建成功！"
    echo "   项目路径: $project_path"
    echo "   可开始创作:"
    echo "   - cd $project_path"
    echo "   - 在 chapters/ 目录下创建章节"
    log "创建新项目: $dir_name ($novel_title)"
}

count_words() {
    echo "请选择项目："
    echo "1. 末日重生_囤货"
    echo "2. 杀了婆婆的我"
    echo "3. 挑战者"
    echo "4. 所有项目"
    read choice
    
    case $choice in
        1) projects=("末日重生_囤货") ;;
        2) projects=("杀了婆婆的我") ;;
        3) projects=("挑战者") ;;
        4) projects=("末日重生_囤货" "杀了婆婆的我" "挑战者") ;;
        *) echo "无效选择"; return 1 ;;
    esac
    
    echo ""
    echo "📊 字数统计"
    echo "-----------"
    
    total_chapters=0
    total_words=0
    
    for project in "${projects[@]}"; do
        project_path="$PROJECTS_DIR/$project"
        
        if [ ! -d "$project_path" ]; then
            echo "❌ 项目不存在: $project"
            continue
        fi
        
        chapter_count=$(find "$project_path/chapters" -name "*.md" 2>/dev/null | wc -l)
        chapter_words=0
        
        if [ $chapter_count -gt 0 ]; then
            for chapter in "$project_path/chapters"/*.md; do
                if [ -f "$chapter" ]; then
                    words=$(wc -w < "$chapter" 2>/dev/null || echo 0)
                    chapter_words=$((chapter_words + words))
                fi
            done
        fi
        
        echo "📖 $project:"
        echo "   章节: $chapter_count 章"
        echo "   字数: $chapter_words 字"
        echo ""
        
        total_chapters=$((total_chapters + chapter_count))
        total_words=$((total_words + chapter_words))
    done
    
    echo "📈 总计:"
    echo "   总章节: $total_chapters 章"
    echo "   总字数: $total_words 字"
    
    log "字数统计: $total_words 字 ($total_chapters 章)"
}

export_backup() {
    echo "请选择要备份的项目："
    echo "1. 末日重生_囤货"
    echo "2. 杀了婆婆的我"
    echo "3. 挑战者"
    echo "4. 所有项目"
    read choice
    
    case $choice in
        1) projects=("末日重生_囤货") ;;
        2) projects=("杀了婆婆的我") ;;
        3) projects=("挑战者") ;;
        4) projects=("末日重生_囤货" "杀了婆婆的我" "挑战者") ;;
        *) echo "无效选择"; return 1 ;;
    esac
    
    BACKUP_DIR="/root/.openclaw/backups/$(date '+%Y%m%d_%H%M%S')"
    mkdir -p "$BACKUP_DIR"
    
    echo ""
    echo "📦 备份项目到: $BACKUP_DIR"
    
    for project in "${projects[@]}"; do
        project_path="$PROJECTS_DIR/$project"
        
        if [ -d "$project_path" ]; then
            # 创建项目备份
            backup_name="${project}_$(date '+%Y%m%d').tar.gz"
            tar -czf "$BACKUP_DIR/$backup_name" -C "$PROJECTS_DIR" "$project"
            
            echo "   ✅ $project -> $backup_name"
        else
            echo "   ❌ $project: 项目不存在"
        fi
    done
    
    # 创建备份信息
    cat > "$BACKUP_DIR/backup_info.md" << BACKUP_EOF
# 备份信息

## 备份时间
$(date '+%Y年%m月%d日 %H:%M:%S')

## 包含项目
$(printf '%s\n' "${projects[@]}")

## 备份位置
$BACKUP_DIR

## 恢复方法
1. 解压备份文件:
   tar -xzf backup_name.tar.gz -C /目标目录
2. 或直接复制整个备份目录
BACKUP_EOF
    
    echo ""
    echo "✅ 备份完成！"
    echo "   备份目录: $BACKUP_DIR"
    
    log "创建备份: $BACKup_DIR (${#projects[@]}个项目)"
}

show_update_log() {
    echo "🔄 更新日志"
    echo "----------"
    
    if [ -f "$LOGFILE" ]; then
        tail -20 "$LOGFILE"
    else
        echo "暂无日志记录"
    fi
}

# 主循环
main() {
    while true; do
        show_menu
        echo "请选择操作 (1-7):"
        read choice
        
        case $choice in
            1) list_projects ;;
            2) show_project_detail ;;
            3) create_new_project ;;
            4) count_words ;;
            5) export_backup ;;
            6) show_update_log ;;
            7) 
                echo "再见！"
                exit 0
                ;;
            *)
                echo "❌ 无效选择，请重新输入"
                ;;
        esac
        
        echo ""
        echo "按回车键继续..."
        read
    done
}

# 启动程序
main