#!/usr/bin/env python3
"""
扫描 + 清理垃圾
遍历 source_dirs，清理空壳目录和小视频残片
读配置文件：与脚本同目录下的 config.json
"""
import os, json, sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

def load_config():
    cfg_path = os.path.join(SCRIPT_DIR, "..", "config.json")
    with open(cfg_path) as f:
        return json.load(f)

def scan_and_clean(cfg):
    src_dirs = cfg["source_dirs"]
    min_size = cfg["min_size_mb"] * 1024 * 1024
    video_exts = {'.mp4','.mkv','.avi','.mov','.wmv','.flv','.webm','.ts','.m4v','.rmvb'}
    
    targets = []
    print("=== 扫描 ===")
    for base in src_dirs:
        if not os.path.isdir(base):
            print(f"  [WARN] 目录不存在: {base}")
            continue
        for entry in sorted(os.listdir(base)):
            full = os.path.join(base, entry)
            if not os.path.isdir(full):
                continue
            total_sz = 0
            real_video = 0
            try:
                for dp, dn, fn in os.walk(full):
                    for f in fn:
                        fp = os.path.join(dp, f)
                        try:
                            total_sz += os.path.getsize(fp)
                        except: pass
                        if os.path.splitext(f)[1].lower() in video_exts:
                            real_video += 1
            except: pass
            
            action = "KEEP"
            if total_sz < min_size and real_video == 0:
                action = "DELETE"
            elif total_sz < min_size and real_video > 0:
                action = "DELETE"
            
            print(f"  [{action:>6}] {entry}  ({total_sz/1024**2:.0f}MB, {real_video}视频)")
            
            if action == "DELETE":
                targets.append(full)
    
    if targets:
        print(f"\n待删除: {len(targets)} 个")
        print("开始删除...")
        import shutil
        for d in targets:
            shutil.rmtree(d)
            print(f"  ✓ 已删: {os.path.basename(d)}")
    else:
        print("\n无需清理。")

if __name__ == "__main__":
    cfg = load_config()
    scan_and_clean(cfg)
