#!/bin/bash

# Git 每日工作脚本
# 用于日常版本管理和备份

set -e

echo "📅 $(date '+%Y-%m-%d %H:%M:%S') - 开始 Git 日常管理..."

# 检查是否有未提交的变更
if [ -n "$(git status --porcelain)" ]; then
    echo "📝 检测到未提交的变更..."
    
    # 显示变更摘要
    echo "变更摘要:"
    git status --short
    
    # 询问是否提交
    read -p "是否提交这些变更？ (y/n): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        # 添加所有变更
        git add .
        
        # 生成提交信息
        commit_msg="chore: 每日备份 $(date '+%Y-%m-%d %H:%M:%S')"
        
        # 如果有特定类型的变更，更新提交信息
        if git diff --cached --name-only | grep -q "novel/.*\.md$"; then
            novel_files=$(git diff --cached --name-only | grep "novel/.*\.md$" | tr '\n' ' ')
            commit_msg="feat(novel): 更新小说内容 - $novel_files"
        elif git diff --cached --name-only | grep -q "\.py$"; then
            script_files=$(git diff --cached --name-only | grep "\.py$" | tr '\n' ' ')
            commit_msg="refactor(scripts): 更新脚本 - $script_files"
        elif git diff --cached --name-only | grep -q "\.md$"; then
            md_files=$(git diff --cached --name-only | grep "\.md$" | tr '\n' ' ')
            commit_msg="docs: 更新文档 - $md_files"
        fi
        
        # 提交
        git commit -m "$commit_msg"
        
        echo "✅ 变更已提交: $commit_msg"
    else
        echo "⏸️ 跳过提交"
    fi
else
    echo "✅ 工作区干净，没有未提交的变更"
fi

# 检查是否有远程仓库
if git remote | grep -q origin; then
    echo "🌐 检测到远程仓库 origin"
    
    # 拉取最新变更
    echo "⬇️ 拉取远程最新变更..."
    git pull origin $(git branch --show-current)
    
    # 推送本地变更
    echo "⬆️ 推送本地变更到远程..."
    git push origin $(git branch --show-current)
    
    echo "✅ 远程同步完成"
else
    echo "⚠️ 未配置远程仓库"
    echo "  使用以下命令添加远程仓库:"
    echo "  git remote add origin <your-repo-url>"
fi

# 显示仓库状态
echo ""
echo "📊 仓库状态:"
git log --oneline -5
echo ""
echo "🎉 Git 日常管理完成！"