#!/bin/bash

# Скрипт для сканирования элементов, которые можно безопасно удалить при регулярной очистке
# Основано на всех итерациях очистки диска

# Цвета для вывода
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

echo "=========================================="
echo "  Сканирование элементов для регулярной очистки"
echo "=========================================="
echo ""

TOTAL_SIZE=0
ITEMS_FOUND=0

# Функция для сканирования директории
scan_dir() {
    local path="$1"
    local name="$2"
    local exclude_protected="$3"
    
    if [ ! -d "$path" ]; then
        return
    fi
    
    # Проверка на защищенные элементы
    if [ "$exclude_protected" = "true" ]; then
        # Проверяем, не является ли это защищенным элементом
        case "$path" in
            *"/Thunderbird"*) return ;;
            *"/Pictures"*) return ;;
            *"/Videos"*) return ;;
            *"/BraveSoftware"*) return ;;
            *"/Steam"*) return ;;
            *"/Whisky"*) return ;;
            *"/gdrive.hoonabku/h.app_bac"*) return ;;
            *"/h.app_bac/"*) return ;;
            *"/Cursor/User/History"*) return ;;
            *"/Cursor/User/workspaceStorage"*) return ;;
            *"/Cursor/extensions"*) return ;;
            *"/Cursor/logs"*) return ;;
            *"/Cursor/CachedData"*) return ;;
            *"/.cursor/ai-tracking"*) return ;;
            *"/pnpm"*) return ;;
            *"/hunabapp-dev/frontend/node_modules"*) return ;;
            *"/.gradle"*) return ;;
            *"/hunabapp-dev/frontend/android/app/build"*) return ;;
            *"/Telegram Desktop"*) return ;;
            *"/anytype"*) return ;;
            *"/direct-commander"*) return ;;
            *"/backup_"*) return ;;
            *"/archives_"*) return ;;
            *"/methatron/pics/tablecloth/1-7.zip"*) return ;;
        esac
    fi
    
    local size=$(du -sm "$path" 2>/dev/null | cut -f1)
    if [ -n "$size" ] && [ "$size" -gt 0 ]; then
        local size_mb=$size
        local size_gb=$(echo "scale=2; $size / 1024" | bc 2>/dev/null || echo "0")
        printf "   %-60s %8sMB (%sGB)\n" "$name" "$size_mb" "$size_gb"
        TOTAL_SIZE=$((TOTAL_SIZE + size))
        ((ITEMS_FOUND++))
    fi
}

# Функция для сканирования файлов по паттерну
scan_files() {
    local pattern="$1"
    local name="$2"
    local exclude_protected="$3"
    
    local total=0
    while IFS= read -r file; do
        if [ -n "$file" ] && [ -f "$file" ]; then
            # Проверка на защищенные элементы
            if [ "$exclude_protected" = "true" ]; then
                case "$file" in
                    *"/backup_"*) continue ;;
                    *"/archives_"*) continue ;;
                    *"/methatron/pics/tablecloth/1-7.zip"*) continue ;;
                    *"/legal/legal_education/books/Martin/.../Дополнительный урок по маркам.rar"*) continue ;;
                esac
            fi
            
            local size=$(du -sm "$file" 2>/dev/null | cut -f1)
            if [ -n "$size" ] && [ "$size" -gt 0 ]; then
                total=$((total + size))
            fi
        fi
    done < <(find ~/code -type f $pattern 2>/dev/null | head -20)
    
    if [ "$total" -gt 0 ]; then
        local size_gb=$(echo "scale=2; $total / 1024" | bc 2>/dev/null || echo "0")
        printf "   %-60s %8sMB (%sGB)\n" "$name" "$total" "$size_gb"
        TOTAL_SIZE=$((TOTAL_SIZE + total))
        ((ITEMS_FOUND++))
    fi
}

echo -e "${CYAN}=== КРИТИЧЕСКИЙ ПРИОРИТЕТ (кэши разработки) ===${NC}"
echo ""

# npm кэш
scan_dir "$HOME/.npm" "npm кэш" true
scan_dir "$HOME/.npm/_npx" "npm npx кэш" true

# node-gyp кэш
scan_dir "$HOME/Library/Caches/node-gyp" "node-gyp кэш" true

# TypeScript кэш
scan_dir "$HOME/Library/Caches/typescript" "TypeScript кэш" true

# pip кэш
scan_dir "$HOME/Library/Caches/pip" "pip кэш" true

# .yarn кэш
scan_dir "$HOME/.yarn" ".yarn кэш" true

# Colima кэш
scan_dir "$HOME/.colima" "Colima кэш" true
scan_dir "$HOME/Library/Caches/colima" "Colima кэш (Library)" true

# Playwright кэш (браузеры для e2e-тестов)
scan_dir "$HOME/Library/Caches/ms-playwright" "Playwright кэш" true

# Codeium/Windsurf кэши
scan_dir "$HOME/.codeium/windsurf" "Codeium/Windsurf кэш" true

echo ""
echo -e "${CYAN}=== node_modules (исключая защищенные) ===${NC}"
echo ""

# node_modules (исключая защищенные)
find ~/code -type d -name "node_modules" \
    -not -path "*/venv/*" \
    -not -path "*/.venv/*" \
    -not -path "*/env/*" \
    -not -path "*/hunabapp-dev/frontend/node_modules" \
    -exec du -sh {} \; 2>/dev/null | sort -hr | head -5 | while read size path; do
    printf "   %-60s %8s\n" "$path" "$size"
    size_mb=$(du -sm "$path" 2>/dev/null | cut -f1)
    if [ -n "$size_mb" ]; then
        TOTAL_SIZE=$((TOTAL_SIZE + size_mb))
        ((ITEMS_FOUND++))
    fi
done

echo ""
echo -e "${CYAN}=== BUILD АРТЕФАКТЫ (исключая защищенные) ===${NC}"
echo ""

# Build артефакты (исключая защищенные)
find ~/code -type d \( -name "build" -o -name "dist" -o -name ".next" -o -name "out" \) \
    -not -path "*/node_modules/*" \
    -not -path "*/venv/*" \
    -not -path "*/.venv/*" \
    -not -path "*/env/*" \
    -not -path "*/site-packages/*" \
    -not -path "*/hunabapp-dev/frontend/android/app/build*" \
    -exec du -sh {} \; 2>/dev/null | sort -hr | head -10 | while read size path; do
    printf "   %-60s %8s\n" "$path" "$size"
    size_mb=$(du -sm "$path" 2>/dev/null | cut -f1)
    if [ -n "$size_mb" ]; then
        TOTAL_SIZE=$((TOTAL_SIZE + size_mb))
        ((ITEMS_FOUND++))
    fi
done

echo ""
echo -e "${CYAN}=== КЭШИ БРАУЗЕРОВ (кроме защищенных) ===${NC}"
echo ""

# Google Chrome кэш
scan_dir "$HOME/Library/Caches/Google" "Google Chrome кэш" true

# Firefox кэш
scan_dir "$HOME/Library/Caches/Firefox" "Firefox кэш" true

# com.brave.Browser кэш (отдельный, не основной)
scan_dir "$HOME/Library/Caches/com.brave.Browser" "Brave Browser кэш (отдельный)" true

echo ""
echo -e "${CYAN}=== КЭШИ ПРИЛОЖЕНИЙ ===${NC}"
echo ""

# Notion
scan_dir "$HOME/Library/Application Support/Notion" "Notion кэш" true

# zoom.us
scan_dir "$HOME/Library/Application Support/zoom.us" "zoom.us кэш" true

# LibreOffice
scan_dir "$HOME/Library/Application Support/LibreOffice" "LibreOffice кэш" true

# Movavi
scan_dir "$HOME/Library/Application Support/Movavi" "Movavi кэш" true

# Ledger Live
scan_dir "$HOME/Library/Application Support/Ledger Live" "Ledger Live кэш" true

# Syncthing
scan_dir "$HOME/Library/Application Support/Syncthing" "Syncthing кэш" true

# ResponsivelyApp
scan_dir "$HOME/Library/Application Support/ResponsivelyApp" "ResponsivelyApp кэш" true
scan_dir "$HOME/Library/Caches/responsivelyapp-updater" "responsivelyapp-updater кэш" true

echo ""
echo -e "${CYAN}=== CURSOR КЭШИ (кроме защищенных) ===${NC}"
echo ""

# Cursor WebStorage
scan_dir "$HOME/Library/Application Support/Cursor/WebStorage" "Cursor WebStorage" true

# Cursor Partitions
scan_dir "$HOME/Library/Application Support/Cursor/Partitions" "Cursor Partitions" true

# Cursor projects
scan_dir "$HOME/.cursor/projects" "Cursor projects" true

# Cursor CachedExtensionVSIXs
scan_dir "$HOME/Library/Application Support/Cursor/CachedExtensionVSIXs" "Cursor CachedExtensionVSIXs" true

# Cursor logs (старые, если есть)
if [ -d "$HOME/Library/Application Support/Cursor/logs" ]; then
    logs_size=$(du -sm "$HOME/Library/Application Support/Cursor/logs" 2>/dev/null | cut -f1)
    if [ -n "$logs_size" ] && [ "$logs_size" -gt 10 ]; then
        printf "   %-60s %8sMB\n" "Cursor logs (старые)" "$logs_size"
        TOTAL_SIZE=$((TOTAL_SIZE + logs_size))
        ((ITEMS_FOUND++))
    fi
fi

# ShipIt кэш
scan_dir "$HOME/Library/Caches/com.todesktop.230313mzl4w4u92.ShipIt" "Cursor ShipIt кэш" true

echo ""
echo -e "${CYAN}=== СИСТЕМНЫЕ КЭШИ ===${NC}"
echo ""

# Homebrew кэш
scan_dir "$HOME/Library/Caches/Homebrew" "Homebrew кэш" true

# anytype-updater кэш
scan_dir "$HOME/Library/Caches/anytype-updater" "anytype-updater кэш" true

# GeoServices кэш
scan_dir "$HOME/Library/Caches/GeoServices" "GeoServices кэш" true

# Apple системные кэши
scan_dir "$HOME/Library/Caches/com.apple.helpd" "com.apple.helpd" true
scan_dir "$HOME/Library/Caches/com.apple.parsecd" "com.apple.parsecd" true
scan_dir "$HOME/Library/Caches/com.apple.appstoreagent" "com.apple.appstoreagent" true
scan_dir "$HOME/Library/Caches/com.apple.CloudTelemetry" "com.apple.CloudTelemetry" true
scan_dir "$HOME/Library/Caches/com.apple.AMPLibraryAgent" "com.apple.AMPLibraryAgent" true
scan_dir "$HOME/Library/Caches/com.apple.AppleMediaServices" "com.apple.AppleMediaServices" true
scan_dir "$HOME/Library/Caches/com.apple.ctcategories.service" "com.apple.ctcategories.service" true
scan_dir "$HOME/Library/Caches/com.apple.amsengagementd" "com.apple.amsengagementd" true
scan_dir "$HOME/Library/Caches/com.apple.tipsd" "com.apple.tipsd" true
scan_dir "$HOME/Library/Caches/com.apple.itunescloudd" "com.apple.itunescloudd" true
scan_dir "$HOME/Library/Caches/com.apple.nbagent" "com.apple.nbagent" true
scan_dir "$HOME/Library/Caches/askpermissiond" "askpermissiond" true
scan_dir "$HOME/Library/Caches/com.apple.python" "com.apple.python" true
scan_dir "$HOME/Library/Caches/audioCache.kcache" "audioCache.kcache" true
scan_dir "$HOME/Library/Caches/Mega" "Mega кэш" true
scan_dir "$HOME/Library/Caches/kdenlive" "kdenlive кэш" true

echo ""
echo -e "${CYAN}=== ЛОГИ ===${NC}"
echo ""

# Логи Google
scan_dir "$HOME/Library/Logs/Google" "Логи Google" true

# Пустые логи
empty_logs=$(find ~/Library/Logs -type f -size 0 2>/dev/null | wc -l | tr -d ' ')
if [ -n "$empty_logs" ] && [ "$empty_logs" -gt 0 ] 2>/dev/null; then
    printf "   %-60s %8s файлов\n" "Пустые логи" "$empty_logs"
fi

echo ""
echo -e "${CYAN}=== PYTHON КЭШИ ===${NC}"
echo ""

# __pycache__ в venv
find ~/code -type d -name "__pycache__" \
    -path "*/venv/*" -o -path "*/.venv/*" -o -path "*/env/*" \
    -exec du -sh {} \; 2>/dev/null | sort -hr | head -10 | while read size path; do
    printf "   %-60s %8s\n" "$path" "$size"
    size_mb=$(du -sm "$path" 2>/dev/null | cut -f1)
    if [ -n "$size_mb" ]; then
        TOTAL_SIZE=$((TOTAL_SIZE + size_mb))
        ((ITEMS_FOUND++))
    fi
done

echo ""
echo -e "${CYAN}=== ЗАПИСИ ЭКРАНА ===${NC}"
echo ""

# ScreenRecordings
scan_dir "$HOME/Library/ScreenRecordings" "ScreenRecordings" true

echo ""
echo -e "${CYAN}=== СТАРЫЕ АРХИВЫ (опционально) ===${NC}"
echo ""

# Старые архивы (исключая защищенные)
find ~/code -type f \( -name "*.zip" -o -name "*.rar" -o -name "*.tar.gz" -o -name "*.7z" \) \
    -not -path "*/backup_*" \
    -not -path "*/archives_*" \
    -not -path "*/methatron/pics/tablecloth/1-7.zip" \
    -size +10M \
    -exec du -sh {} \; 2>/dev/null | sort -hr | head -10 | while read size path; do
    printf "   %-60s %8s\n" "$path" "$size"
    size_mb=$(du -sm "$path" 2>/dev/null | cut -f1)
    if [ -n "$size_mb" ]; then
        TOTAL_SIZE=$((TOTAL_SIZE + size_mb))
        ((ITEMS_FOUND++))
    fi
done

echo ""
echo -e "${CYAN}=== GIT РЕПОЗИТОРИИ (для оптимизации, не удаление) ===${NC}"
echo ""

# Git репозитории для оптимизации
find ~/code -type d -name ".git" -exec sh -c '
    repo=$(dirname "$1")
    git_size=$(du -sm "$repo/.git" 2>/dev/null | cut -f1)
    if [ -n "$git_size" ] && [ "$git_size" -gt 100 ]; then
        printf "   %-60s %8sMB\n" "$repo" "$git_size"
    fi
' _ {} \; 2>/dev/null | sort -k2 -nr | head -5

echo ""
echo "=========================================="
echo -e "  ${GREEN}ИТОГИ СКАНИРОВАНИЯ${NC}"
echo "=========================================="
echo ""
echo -e "Найдено элементов для очистки: ${YELLOW}$ITEMS_FOUND${NC}"
echo ""

if [ "$TOTAL_SIZE" -gt 0 ]; then
    total_gb=$(echo "scale=2; $TOTAL_SIZE / 1024" | bc 2>/dev/null || echo "0")
    echo -e "Общий размер: ${GREEN}${TOTAL_SIZE}MB (~${total_gb}GB)${NC}"
else
    echo -e "Общий размер: ${GREEN}0MB${NC}"
fi

echo ""
echo -e "${YELLOW}⚠️  ВАЖНО:${NC}"
echo "   - Защищённые элементы: docs/disk_cleanup/DO_NOT_DELETE.md"
echo "   - Проверьте список перед удалением"
echo "   - Некоторые элементы могут быть пересозданы автоматически"
echo ""
echo -e "${BLUE}💡 РЕКОМЕНДАЦИИ:${NC}"
echo "   - Для регулярной очистки используйте: REGULAR_CLEANUP.md"
echo "   - Главный документ: DISK_CLEANUP.md"
echo ""



