#!/usr/bin/env python3
"""
按关键词规则分类归档 /mnt/f/collections + /mnt/f/video 到 /mnt/f 下的大类目录
"""
import os, shutil, json

SRC = ["/mnt/f/collections", "/mnt/f/video"]
BASE = "/mnt/f"

# 目标大类目录（自动创建）
CATEGORIES = {
    "过那条巷子": ("过那条巷子", ["过那条巷子"]),
    "2048合集":   ("2048合集", ["2048"]),
    "AI短剧":     ("AI短剧", ["AI短剧","AI自制","AI视频","美丽新世界","少年阿宾","NTR寝取",
                             "嫂子","魔女小姨子","桃运圣医","我和老师的约定"]),
    "FC2福利姬":  ("FC2福利姬", ["FC2","Comatozze","Dainty","KAKAE","lananlanan","P站"]),
    "合集种子":   ("合集种子", ["BT-btt"]),
    "国产露脸":   ("国产露脸", ["19岁","冯帆","momocats","露脸才是王道","香蕉"]),
    "自拍泄漏":   ("自拍泄漏", ["泄密","自拍","自慰","原相机","情侣","校花","嫩妹","福利姬",
                              "裸聊","绿帽","良家","约炮","狗哥","土豪","原档","维度",
                              "桃子","娇娇","学妹","反差"]),
}

KEEP_AS_IS = {"重生之征服郭伯母"}

def classify(name):
    """返回目标目录名或 None"""
    if name in KEEP_AS_IS:
        return None
    for cat_name, (dir_name, keywords) in CATEGORIES.items():
        if any(k in name for k in keywords):
            return os.path.join(BASE, dir_name)
    return os.path.join(BASE, "AI短剧")  # 兜底

moves = []
for base in SRC:
    if not os.path.isdir(base):
        continue
    for entry in sorted(os.listdir(base)):
        full = os.path.join(base, entry)
        if not os.path.isdir(full):
            continue
        dst_base = classify(entry)
        if dst_base is None:
            print(f"  ○ 不动: {entry}")
            continue
        dst = os.path.join(dst_base, entry)
        if os.path.exists(dst):
            i = 1
            while os.path.exists(f"{dst}_{i}"): i += 1
            dst = f"{dst}_{i}"
        moves.append((full, dst))

# 创建目录
all_dirs = set(os.path.dirname(d) for _, d in moves)
for d in all_dirs:
    os.makedirs(d, exist_ok=True)

# 执行移动
print(f"开始移动 {len(moves)} 个条目...")
for src, dst in moves:
    try:
        shutil.move(src, dst)
        print(f"  ✓ {os.path.basename(src)}")
    except Exception as e:
        print(f"  ✗ {os.path.basename(src)} -> {e}")

# 清理空目录
for d in SRC:
    if os.path.isdir(d) and not os.listdir(d):
        os.rmdir(d)
        print(f"  ✓ 已删空目录: {d}")

# 报告
print("\n=== /mnt/f 最终结构 ===")
for d in sorted(os.listdir(BASE)):
    full = os.path.join(BASE, d)
    if os.path.isdir(full):
        sz = 0
        cnt = 0
        for dp, dn, fn in os.walk(full):
            for f in fn:
                cnt += 1
                try: sz += os.path.getsize(os.path.join(dp, f))
                except: pass
        print(f"  {d}/  ({cnt} 文件, {sz/1024**3:.1f}GB)")
