import os
import sys

# 要移除的關鍵字（可出現在檔名或資料夾名稱中的任意位置）
substrings_to_remove = [
    "dccdom.com@",
    "麻豆傳媒",
    "-uncensored-nyap2p.com",
	"WoXav.Com@",
    "Woxav.Com@",
	"kckc17.com@",
	"aavv121.com@",
    "avav77.xyz@",
	"4k2.com@",
	"-nyap2p.com",
    "rh20s8.com ",
	"rh2048.com",
	"hhd800.com@",
	"2048论坛rh2048.com @",
	"kckc16.com@",
	"kfa55.com@",
    "kckc14.com@",
    "kfa33.com@",
    "rh20s8.com PornWorld - ",
    "_www.javhdbbs.com",
    "-Pornhub.com",
    "freedl.org@"
]

def resolve_name_conflict(root, new_name):
    base, ext = os.path.splitext(new_name)
    counter = 1
    candidate = new_name
    while os.path.exists(os.path.join(root, candidate)):
        candidate = f"{base}_{counter}{ext}"
        counter += 1
    return candidate

def clean_name(name):
    new_name = name
    for substring in substrings_to_remove:
        new_name = new_name.replace(substring, "")
    return new_name

def rename_items_in_directory(target_dir):
    if not os.path.isdir(target_dir):
        print(f"❌ 指定的路徑不存在或不是資料夾: {target_dir}")
        return

    for root, dirs, files in os.walk(target_dir, topdown=False):
        # 檔案
        for name in files:
            original_path = os.path.join(root, name)
            new_name = clean_name(name)
            if new_name != name:
                new_name = resolve_name_conflict(root, new_name)
                new_path = os.path.join(root, new_name)
                os.rename(original_path, new_path)
                print(f"[檔案] ✅ {original_path} ➜ {new_path}")

        # 資料夾
        for name in dirs:
            original_path = os.path.join(root, name)
            new_name = clean_name(name)
            if new_name != name:
                new_name = resolve_name_conflict(root, new_name)
                new_path = os.path.join(root, new_name)
                os.rename(original_path, new_path)
                print(f"[資料夾] ✅ {original_path} ➜ {new_path}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("用法: python3 rename_file.py <目標路徑>")
        sys.exit(1)

    target_path = sys.argv[1]
    rename_items_in_directory(target_path)
