#!/usr/bin/env python3.11
import shutil
from pathlib import Path

TARGET_DIR = Path("/home/dayhanbiz/public_html/3-damja.science/depository/Необработанные поступления")

def flatten_directory():
    if not TARGET_DIR.exists():
        print(f"[ОШИБКА] Папка не найдена: {TARGET_DIR}")
        return

    print(f"=== ПЕРЕМЕЩЕНИЕ ВСЕХ ФАЙЛОВ В КОРЕНЬ: {TARGET_DIR.name} ===\n")

    # Берём только файлы из поддиректорий (пропуская те, что уже в корне)
    nested_files = [f for f in TARGET_DIR.rglob('*') if f.is_file() and f.parent != TARGET_DIR and not f.name.startswith('.')]

    print(f"Найдено файлов во вложенных папках: {len(nested_files)}")

    moved_count = 0

    for file_path in nested_files:
        target_path = TARGET_DIR / file_path.name

        # Разрешение конфликтов имён (добавление _1, _2 и т.д.)
        if target_path.exists():
            stem = file_path.stem
            suffix = file_path.suffix
            counter = 1
            while target_path.exists():
                target_path = TARGET_DIR / f"{stem}_{counter}{suffix}"
                counter += 1

        try:
            shutil.move(str(file_path), str(target_path))
            moved_count += 1
        except Exception as e:
            print(f"[ОШИБКА] Не удалось переместить {file_path.name}: {e}")

    # Очистка пустых поддиректорий
    removed_dirs = 0
    for sub_dir in sorted(TARGET_DIR.rglob('*'), reverse=True):
        if sub_dir.is_dir() and sub_dir != TARGET_DIR:
            try:
                sub_dir.rmdir()
                removed_dirs += 1
            except OSError:
                pass # Папка не пуста

    print("\n================ ИТОГИ ================")
    print(f"Перемещено файлов в корень: {moved_count}")
    print(f"Удалено пустых подпапок:    {removed_dirs}")
    print("=======================================")

if __name__ == "__main__":
    flatten_directory()
