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

# Исходные директории
SOURCE_DIRS = [
    Path("/home/dayhanbiz/public_html/3-damja.science/storage/history_pdf"),
    Path("/home/dayhanbiz/public_html/3-damja.science/storage/history_books")
]

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

def calculate_sha256(file_path: Path, chunk_size: int = 65536) -> str:
    """Вычисляет SHA-256 хэш файла."""
    hasher = hashlib.sha256()
    try:
        with open(file_path, 'rb') as f:
            while chunk := f.read(chunk_size):
                hasher.update(chunk)
        return hasher.hexdigest()
    except Exception as e:
        print(f"   [ОШИБКА ЧТЕНИЯ] {file_path.name}: {e}")
        return ""

def move_history_files():
    if not TARGET_DIR.exists():
        TARGET_DIR.mkdir(parents=True, exist_ok=True)

    print("=== ИНДЕКСАЦИЯ СУЩЕСТВУЮЩИХ ФАЙЛОВ В ЦЕЛЕВОЙ ПАПКЕ ===")
    target_hashes = {}
    
    # Индексируем файлы, которые уже лежат в целевой папке
    existing_files = [f for f in TARGET_DIR.iterdir() if f.is_file() and not f.name.startswith('.')]
    print(f"Найдено имеющихся файлов в папке назначения: {len(existing_files)}")
    
    for f in existing_files:
        f_hash = calculate_sha256(f)
        if f_hash:
            target_hashes[f_hash] = f

    print("\n=== НАЧАЛО ПЕРЕМЕЩЕНИЯ ФАЙЛОВ ===")
    
    scanned_count = 0
    moved_count = 0
    duplicate_count = 0

    for source_dir in SOURCE_DIRS:
        if not source_dir.exists():
            print(f"[ПРОПУСК] Папка не найдена: {source_dir}")
            continue

        print(f"\nСканирование папки: {source_dir}")
        source_files = [f for f in source_dir.rglob('*') if f.is_file() and not f.name.startswith('.')]

        for src_file in source_files:
            scanned_count += 1
            src_hash = calculate_sha256(src_file)

            if not src_hash:
                continue

            # Проверка на полное совпадение по содержимому
            if src_hash in target_hashes:
                print(f"[ДУБЛИКАТ] Удаляем исходный: {src_file.name}")
                try:
                    src_file.unlink()
                    duplicate_count += 1
                except Exception as e:
                    print(f"   Ошибка при удалении дубликата: {e}")
            else:
                # Файл уникальный, готовим имя для целевой папки
                target_path = TARGET_DIR / src_file.name

                # Если совпадает только имя, но содержимое разное — меняем имя
                if target_path.exists():
                    stem = src_file.stem
                    suffix = src_file.suffix
                    counter = 1
                    while target_path.exists():
                        target_path = TARGET_DIR / f"{stem}_{counter}{suffix}"
                        counter += 1

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

        # Удаление пустых подпапок в источнике
        for sub_dir in sorted(source_dir.rglob('*'), reverse=True):
            if sub_dir.is_dir():
                try:
                    sub_dir.rmdir()
                except OSError:
                    pass

    print("\n================ ИТОГИ ================")
    print(f"Всего найдено файлов:      {scanned_count}")
    print(f"Успешно перемещено:         {moved_count}")
    print(f"Пропущено дубликатов:      {duplicate_count}")
    print("=======================================")

if __name__ == "__main__":
    move_history_files()
