#!/usr/bin/env python3
"""
网红开篇素材批量重命名脚本
============================

按规则 md5(父目录名_原文件名) 重命名本地视频文件。

用法：
    python3 scripts/rename_viral_opening.py

效果：
    /Users/0fun/Desktop/网红开篇/恶搞开篇/暴力拆除-恶搞开篇/5月16日(13).mp4
    → /Users/0fun/Desktop/网红开篇/恶搞开篇/暴力拆除-恶搞开篇/2eaf1185....mp4
"""

import hashlib
import json
from pathlib import Path


def md5_filename(parent_name: str, original_name: str) -> str:
    raw = f"{parent_name}_{original_name}"
    return hashlib.md5(raw.encode("utf-8")).hexdigest() + ".mp4"


def main():
    src_dir = Path("/Users/0fun/Desktop/网红开篇")
    renamed = []

    for mp4_file in sorted(src_dir.rglob("*.mp4")):
        if mp4_file.name.startswith("."):
            continue

        parent_folder = mp4_file.parent.name
        original_name = mp4_file.name
        new_name = md5_filename(parent_folder, original_name)

        if mp4_file.name == new_name:
            continue  # 已经重命名过

        new_path = mp4_file.parent / new_name

        print(f"{original_name}\n  → {new_name}")
        mp4_file.rename(new_path)
        renamed.append({
            "original": original_name,
            "new": new_name,
            "folder": parent_folder,
            "path": str(new_path),
        })

    print(f"\n✅ 共重命名 {len(renamed)} 个文件")

    # 保存重命名记录
    record = Path(__file__).parent / "viral_opening_renamed.json"
    with open(record, "w", encoding="utf-8") as f:
        json.dump(renamed, f, ensure_ascii=False, indent=2)
    print(f"📄 记录已保存: {record}")


if __name__ == "__main__":
    main()
