#!/bin/bash

# 检查已暂存的文件大小（大于100KB则警告）
check_file_sizes() {
    local max_size=102400  # 100KB in bytes
    local large_files=()
    
    # 获取Git仓库根目录
    local repo_root
    repo_root=$(git rev-parse --show-toplevel) || exit 1
    
    # 获取已暂存的文件，正确处理带空格的文件名
    while IFS= read -r -d '' file; do
        if [[ -n "$file" ]]; then
            # 构建完整文件路径
            local full_path="$repo_root/$file"
            if [[ -f "$full_path" ]]; then
                # 使用引号确保正确处理带空格的文件名
                file_size=$(stat -c%s "$full_path" 2>/dev/null || stat -f%z "$full_path" 2>/dev/null)
                if [[ $file_size -gt $max_size ]]; then
                    # 在输出时正确转义文件名
                    printf -v escaped_file "%q" "$file"
                    large_files+=("$escaped_file ($((file_size/1024))KB)")
                fi
            fi
        fi
    done < <(git diff --cached --name-only -z --diff-filter=AM)
    
    if [[ ${#large_files[@]} -gt 0 ]]; then
        echo "❌ 发现以下已暂存文件超过100KB，请检查是否需要提交："
        for file_info in "${large_files[@]}"; do
            echo "  $file_info"
        done
        echo ""
        echo "如果需要强制提交，请使用："
        echo "  git commit --no-verify"
        echo ""
        return 1
    fi
    
    return 0
}

# 执行检查
check_file_sizes