# -*- coding: utf-8 -*-
"""
videoclean - 本地视频批量处理：内部去重 + 去广告。

用法（双击运行或 python videoclean.py）：
  1. 输入要处理的文件夹路径（直接回车 = 脚本所在文件夹）。
  2. 广告库：第一次先指定一个广告文件夹（里面放广告视频），脚本算出
     广告 hash 存进同目录的 videoclean-ads.json；以后再指定广告文件夹，
     新广告 hash 会追加进库。没有广告要去的直接回车跳过。
  3. 脚本扫描目标文件夹里的视频，快速算头部 hash（默认开头 1MB 的
     SHA-256，与 hashscan 同一算法），判定口径 = 头部 hash + 文件大小。
  4. 广告视频、重复视频（每组只留一份在原地）集中移进目标文件夹下的
     「_重复与广告」文件夹（分「广告」「重复」两个子文件夹，按原相对
     路径存放）。移动前列清单，直接回车即移动，输入 n 取消。

命令行：
  python videoclean.py D:\\视频
  python videoclean.py D:\\视频 --ads D:\\广告样本
  python videoclean.py D:\\视频 --head-size 2 --yes

只用 Python 标准库，不联网。头部 hash 说明：只看文件开头一段，头部与
大小都相同才判重复/广告；极少数头部相同、后面不同的文件可能误判，
移动前请看清清单。
"""

import hashlib
import json
import os
import shutil
import sys
import time

VIDEO_EXTS = {
    ".mp4", ".mkv", ".avi", ".mov", ".wmv", ".flv", ".webm", ".m4v",
    ".mpg", ".mpeg", ".ts", ".m2ts", ".3gp", ".rmvb", ".vob", ".ogv",
}
QUARANTINE_NAME = "_重复与广告"
ADS_FILE_NAME = "videoclean-ads.json"
DEFAULT_HEAD_MB = 1.0
CHUNK = 1024 * 1024


def script_dir():
    try:
        return os.path.dirname(os.path.abspath(__file__))
    except NameError:
        return os.getcwd()


def sha256_head(path, head_bytes):
    h = hashlib.sha256()
    remaining = head_bytes
    with open(path, "rb") as f:
        while remaining > 0:
            chunk = f.read(min(CHUNK, remaining))
            if not chunk:
                break
            h.update(chunk)
            remaining -= len(chunk)
    return h.hexdigest()


def scan_videos(root, exclude_dirs):
    out = []
    root = os.path.abspath(root)
    excludes = [os.path.abspath(d) for d in exclude_dirs if d]
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [
            d for d in dirnames
            if os.path.abspath(os.path.join(dirpath, d)) not in excludes
        ]
        for name in filenames:
            if os.path.splitext(name)[1].lower() in VIDEO_EXTS:
                out.append(os.path.join(dirpath, name))
    out.sort()
    return out


def hash_files(paths, head_bytes, label):
    """返回 {path: (hash, size)}，失败的文件跳过并计数。"""
    result = {}
    failed = 0
    total = len(paths)
    for i, p in enumerate(paths, 1):
        try:
            size = os.path.getsize(p)
            result[p] = (sha256_head(p, head_bytes), size)
        except OSError as e:
            failed += 1
            print("  跳过（读不了）：%s（%s）" % (p, e))
        if total > 20 and (i % 20 == 0 or i == total):
            print("\r  %s %d/%d" % (label, i, total), end="", flush=True)
    if total > 20:
        print()
    return result, failed


def load_ads():
    path = os.path.join(script_dir(), ADS_FILE_NAME)
    if not os.path.exists(path):
        return {"format": "videoclean-ads", "version": 1,
                "head_mb": DEFAULT_HEAD_MB, "ads": []}, path
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        if data.get("format") != "videoclean-ads":
            raise ValueError("格式不对")
        data.setdefault("ads", [])
        data.setdefault("head_mb", DEFAULT_HEAD_MB)
        return data, path
    except (OSError, ValueError) as e:
        print("广告库文件读不了（%s），按空库处理，原文件保留不动。" % e)
        return {"format": "videoclean-ads", "version": 1,
                "head_mb": DEFAULT_HEAD_MB, "ads": []}, path


def save_ads(data, path):
    tmp = path + ".tmp"
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=1)
    os.replace(tmp, path)


def add_ads_from_folder(ads_data, folder, head_bytes):
    videos = scan_videos(folder, [])
    if not videos:
        print("广告文件夹里没有视频文件：%s" % folder)
        return 0
    print("正在算广告 hash（%d 个视频）…" % len(videos))
    hashed, _ = hash_files(videos, head_bytes, "广告")
    known = {(a["hash"], a["size"]) for a in ads_data["ads"]}
    added = 0
    for p, (h, size) in hashed.items():
        if (h, size) in known:
            continue
        ads_data["ads"].append({
            "hash": h, "size": size,
            "name": os.path.basename(p),
            "added": time.strftime("%Y-%m-%d %H:%M:%S"),
        })
        known.add((h, size))
        added += 1
    print("广告库新增 %d 条，现有 %d 条。" % (added, len(ads_data["ads"])))
    return added


def unique_dest(dest):
    if not os.path.exists(dest):
        return dest
    base, ext = os.path.splitext(dest)
    n = 2
    while os.path.exists("%s (%d)%s" % (base, n, ext)):
        n += 1
    return "%s (%d)%s" % (base, n, ext)


def move_files(moves):
    """moves: [(src, dest)]，返回 (成功, 失败)。"""
    ok = fail = 0
    for src, dest in moves:
        try:
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            dest = unique_dest(dest)
            shutil.move(src, dest)
            ok += 1
        except OSError as e:
            fail += 1
            print("  移动失败：%s（%s）" % (src, e))
    return ok, fail


def fmt_size(b):
    return "%.1f MiB" % (b / 1048576.0)


def run(target, ads_folder, head_mb, assume_yes, interactive):
    target = os.path.abspath(target)
    if not os.path.isdir(target):
        print("文件夹不存在：%s" % target)
        return 1
    quarantine = os.path.join(target, QUARANTINE_NAME)
    ads_data, ads_path = load_ads()
    if ads_data.get("head_mb") != head_mb and ads_data["ads"]:
        print("注意：广告库是按头部 %s MB 建的，本次用 %s MB，广告可能匹配不上。"
              % (ads_data.get("head_mb"), head_mb))
    head_bytes = max(1024, int(head_mb * 1024 * 1024))

    if ads_folder:
        if os.path.abspath(ads_folder) == target:
            print("广告文件夹不能和要处理的文件夹是同一个。")
            return 1
        if not os.path.isdir(ads_folder):
            print("广告文件夹不存在：%s" % ads_folder)
            return 1
        add_ads_from_folder(ads_data, ads_folder, head_bytes)
        ads_data["head_mb"] = head_mb
        save_ads(ads_data, ads_path)
        print("广告库已保存：%s" % ads_path)

    excludes = [quarantine]
    if ads_folder:
        excludes.append(os.path.abspath(ads_folder))
    videos = scan_videos(target, excludes)
    print("目标文件夹共 %d 个视频，正在算头部 hash…" % len(videos))
    if not videos:
        print("没有要处理的视频。")
        return 0
    hashed, failed = hash_files(videos, head_bytes, "扫描")
    ad_keys = {(a["hash"], a["size"]) for a in ads_data["ads"]}

    ad_moves, dup_moves = [], []
    groups = {}
    for p in videos:
        if p not in hashed:
            continue
        key = hashed[p]
        if key in ad_keys:
            rel = os.path.relpath(p, target)
            ad_moves.append((p, os.path.join(quarantine, "广告", rel)))
        else:
            groups.setdefault(key, []).append(p)
    dup_groups = 0
    for key, ps in groups.items():
        if len(ps) < 2:
            continue
        dup_groups += 1
        ps.sort(key=lambda x: (x.count(os.sep), len(x), x))
        for p in ps[1:]:
            rel = os.path.relpath(p, target)
            dup_moves.append((p, os.path.join(quarantine, "重复", rel)))

    total_bytes = sum(hashed[p][1] for p, _ in ad_moves + dup_moves if p in hashed)
    print("扫描完成：视频 %d 个，读失败 %d 个。" % (len(hashed), failed))
    print("广告视频 %d 个；重复 %d 组、要移走 %d 个（每组留一份在原地）；合计移走 %s。"
          % (len(ad_moves), dup_groups, len(dup_moves), fmt_size(total_bytes)))
    moves = ad_moves + dup_moves
    if not moves:
        print("没有广告、没有重复，不用动。")
        return 0
    print("将移到：%s" % quarantine)
    shown = 0
    for src, _ in moves:
        if shown >= 30:
            print("  ……还有 %d 个" % (len(moves) - shown))
            break
        kind = "广告" if (src, _) in ad_moves else "重复"
        print("  [%s] %s" % (kind, os.path.relpath(src, target)))
        shown += 1
    if not assume_yes:
        try:
            ans = input("直接回车即移动，输入 n 取消：").strip().lower()
        except EOFError:
            ans = "n"
        if ans in ("n", "no"):
            print("已取消，文件没动。")
            return 0
    ok, fail = move_files(moves)
    print("移动完成：成功 %d 个，失败 %d 个。集中在 %s" % (ok, fail, quarantine))
    return 0


def parse_args(argv):
    target = None
    ads_folder = None
    head_mb = DEFAULT_HEAD_MB
    assume_yes = False
    i = 0
    while i < len(argv):
        a = argv[i]
        if a == "--ads" and i + 1 < len(argv):
            ads_folder = argv[i + 1]; i += 2
        elif a == "--head-size" and i + 1 < len(argv):
            head_mb = float(argv[i + 1]); i += 2
        elif a == "--yes":
            assume_yes = True; i += 1
        elif a in ("-h", "--help"):
            print(__doc__)
            return None
        elif not a.startswith("-") and target is None:
            target = a; i += 1
        else:
            i += 1
    return target, ads_folder, head_mb, assume_yes


def main():
    parsed = parse_args(sys.argv[1:])
    if parsed is None:
        return 0
    target, ads_folder, head_mb, assume_yes = parsed
    interactive = target is None
    print("videoclean：本地视频批量处理（内部去重 + 去广告）")
    print("重复判定：头部 hash（开头 %g MB）+ 文件大小；重复只留一份在原地，"
          "广告与重复集中移进「%s」。" % (head_mb, QUARANTINE_NAME))
    ads_data, _ = load_ads()
    print("广告库现有 %d 条。" % len(ads_data["ads"]))
    if interactive:
        try:
            target = input("要处理的文件夹路径（直接回车 = 脚本所在文件夹）：").strip().strip('"')
            if not target:
                target = script_dir()
            ads_in = input("广告文件夹路径（回车跳过，用已有广告库）：").strip().strip('"')
            if ads_in:
                ads_folder = ads_in
        except EOFError:
            print("没有输入，已退出。")
            return 1
    try:
        rc = run(target, ads_folder, head_mb, assume_yes, interactive)
    except KeyboardInterrupt:
        print("\n已中断。")
        rc = 1
    if interactive:
        try:
            input("按 Enter 退出…")
        except EOFError:
            pass
    return rc


if __name__ == "__main__":
    sys.exit(main())
