#!/usr/bin/env python3
import os
import hashlib
import json
import sys

# Katalog bazowy – tu wskaż ten, który chcesz patchem objąć
BASE_DIR = os.path.abspath(os.path.dirname(__file__))

# Nazwa pliku wynikowego
OUTPUT_FILE = os.path.join(BASE_DIR, 'Patcher.json')

# Lista plików, które chcemy pominąć w JSON
EXCLUDE_FILES = {
    os.path.basename(__file__),          # ten skrypt
    os.path.basename(OUTPUT_FILE),       # wynikowy JSON
    'news.html',
    'index.html'
}

# Foldery, które chcemy pominąć
EXCLUDE_DIRS = {
    'mobile',
    'BackupOldClient'
}


def compute_md5(path, chunk_size=8192):
    """Oblicza sumę MD5 pliku podanego w 'path'."""
    md5 = hashlib.md5()
    with open(path, 'rb') as f:
        while chunk := f.read(chunk_size):
            md5.update(chunk)
    return md5.hexdigest()


def print_progress(current, total, bar_length=40):
    """Prosty pasek postępu w terminalu."""
    percent = current / total
    arrow = '#' * int(bar_length * percent)
    spaces = '-' * (bar_length - len(arrow))
    sys.stdout.write(f'\rPrzetwarzanie: [{arrow}{spaces}] {int(percent * 100)}%')
    sys.stdout.flush()


def collect_files(base_dir):
    """Przechodzi przez katalog base_dir i zbiera info o plikach (Path, Hash, Size)."""
    entries = []

    # Najpierw zbieramy listę plików (z pominięciem wykluczonych)
    all_files = []
    for root, dirs, files in os.walk(base_dir):
        # Pomijamy katalogi z EXCLUDE_DIRS
        dirs[:] = [d for d in dirs if d not in EXCLUDE_DIRS]

        for fname in files:
            if fname in EXCLUDE_FILES:
                continue
            full_path = os.path.join(root, fname)
            all_files.append(full_path)

    total = len(all_files)
    for i, full_path in enumerate(all_files, start=1):
        rel_path = os.path.relpath(full_path, base_dir).replace(os.sep, '/')
        size = os.path.getsize(full_path)
        hash_md5 = compute_md5(full_path)

        entries.append({
            "Path": rel_path,
            "Hash": hash_md5,
            "Size": size
        })

        print_progress(i, total)

    print()  # nowa linia po pasku postępu
    return entries


def main():
    files = collect_files(BASE_DIR)
    with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
        json.dump(files, f, indent=2, ensure_ascii=False)
    print(f'Wygenerowano {len(files)} wpisów w {OUTPUT_FILE}')


if __name__ == '__main__':
    main()