import os
import sys

DRY_RUN = False
OVERWRITE_EXISTING = True # Zmień na True, jeśli chcesz nadpisywać istniejące docelowe pliki

sys.stdout.reconfigure(errors='replace')

MOJIBAKE_MAP = {
    'ê': 'ł',
    '⌐': 'ę',
    'Ñ': 'ą',
    'ÿ': 'ś',
    '╛': 'ż',
    'ÔîÉ': 'ę',
    '─Ö': 'ę',
    '├│': 'ó',
    '┼é': 'ł',
    '┼ü': 'Ł',
    '─ů': 'ą',
    '┼Ť': 'Ś',
    '┼╝': 'ż',
    '├┐': 'ś',
    '┼â': 'Ń',
    '┼ä': 'ń',
    '┼╣': 'Ź',
    '┼║': 'ź',
    '├Ĺ': 'Ą',
    '├¬': 'ł',
}

def repair_string(text):
    fixed_text = text
    for bad_char, good_char in MOJIBAKE_MAP.items():
        fixed_text = fixed_text.replace(bad_char, good_char)

    if fixed_text != text:
        return fixed_text

    for enc in ['cp437', 'cp852', 'cp1250', 'iso-8859-2', 'cp1252']:
        try:
            candidate = text.encode(enc).decode('utf-8')
            if candidate != text and '\ufffd' not in candidate:
                return candidate
        except (UnicodeEncodeError, UnicodeDecodeError):
            pass

    return text

def get_unique_path(path):
    if not os.path.exists(path):
        return path
    
    base, ext = os.path.splitext(path)
    counter = 1
    new_path = f"{base}_{counter}{ext}"
    while os.path.exists(new_path):
        counter += 1
        new_path = f"{base}_{counter}{ext}"
    return new_path

def fix_names_dfs(current_path='.'):
    try:
        entries = os.listdir(current_path)
    except PermissionError:
        return

    for entry in entries:
        full_path = os.path.join(current_path, entry)
        if os.path.isdir(full_path) and not os.path.islink(full_path):
            fix_names_dfs(full_path)

    try:
        current_entries = os.listdir(current_path)
    except PermissionError:
        return

    for entry in current_entries:
        full_path = os.path.join(current_path, entry)
        new_entry = repair_string(entry)

        if new_entry != entry:
            target_path = os.path.join(current_path, new_entry)

            if os.path.exists(target_path) and not OVERWRITE_EXISTING:
                final_path = get_unique_path(target_path)
            else:
                final_path = target_path

            if DRY_RUN:
                print(f"[ZNALAZŁO] {full_path} -> {final_path}")
            else:
                try:
                    if os.path.exists(target_path) and OVERWRITE_EXISTING:
                        os.replace(full_path, final_path)
                    else:
                        os.rename(full_path, final_path)
                    print(f"[ZMIENIONO] {full_path} -> {final_path}")
                except Exception as e:
                    print(f"[BŁĄD] {full_path}: {e}")

if __name__ == '__main__':
    if DRY_RUN:
        print("TRYB TESTOWY (DRY_RUN = True)\n")
    else:
        print("TRYB REALNY (DRY_RUN = False)\n")

    fix_names_dfs('.')
