# 回退 · 课堂演示件
#
# 作用：读取 改名记录.txt，把文件名改回执行之前的样子。
# 用法：与 第10章演示_批量改名.py 放在同一位置。
#       DRY_RUN 为 True 时只打印不改动，核对无误后改为 False 再运行一次。

from pathlib import Path

# ===== 设置区 =====
FOLDER = '测试文件夹'      # 被改名的文件夹
DRY_RUN = True             # True 为预演，只打印不改动；False 为真正还原
# =================

folder = Path(__file__).with_name(FOLDER)
log = Path(__file__).with_name('改名记录.txt')

# ① 记录不存在就无法还原，先说明情况再结束
if not log.exists():
    print('没有找到 改名记录.txt，无法还原。')
    print('改名记录只在真正执行时写入，事后无法补写。')
    input('按回车键结束')
    raise SystemExit

# ② 逐行读取记录，每行的格式为「新名称 <- 原名称」
lines = log.read_text(encoding='utf-8').splitlines()

done = 0

# ③ 循环：按记录把每一个文件改回原名
for line in lines:
    if ' <- ' not in line:
        continue
    new_name, old_name = line.split(' <- ')
    current = folder / new_name.strip()
    target = folder / old_name.strip()

    # ④ 文件已被移走或再次改名时，跳过并说明
    if not current.exists():
        print('找不到', current.name, '，跳过')
        continue

    print(current.name, '→', target.name)
    done = done + 1

    # ⑤ 预演状态下不做实际改动
    if not DRY_RUN:
        current.rename(target)

# ⑥ 还原完成后提示结果
print()
if DRY_RUN:
    print('以上为预演结果，共', done, '个文件可还原。')
    print('核对无误后，把设置区的 DRY_RUN 改为 False，再运行一次。')
else:
    print('已还原', done, '个文件。')

input('按回车键结束')
