# -*- coding: utf-8 -*-
"""批量下载冯大全全部视频（断点续传 + 重试）"""
import json, os, sys, time, requests

ROOT = r"D:\Deepseek\douyin_fengdaquan"
OUT = os.path.join(ROOT, "videos")
os.makedirs(OUT, exist_ok=True)
rows = json.load(open(os.path.join(ROOT, "_download_list.json"), encoding="utf-8"))

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36")
HEAD = {"User-Agent": UA, "Referer": "https://www.douyin.com/", "Accept": "*/*"}

def target(r):
    return os.path.join(OUT, f"{r['date']}_{r['id']}.mp4")

def download(r, tries=3):
    fp = target(r)
    for attempt in range(1, tries + 1):
        have = os.path.getsize(fp) if os.path.exists(fp) else 0
        h = dict(HEAD)
        if have:
            h["Range"] = f"bytes={have}-"
        try:
            with requests.get(r["url"], headers=h, stream=True, timeout=60) as resp:
                if have and resp.status_code == 200:
                    have = 0  # 服务端不支持续传，重头下
                    mode = "wb"
                elif resp.status_code in (200, 206):
                    mode = "ab" if have else "wb"
                else:
                    raise RuntimeError(f"HTTP {resp.status_code}")
                total = int(resp.headers.get("Content-Length") or 0) + have
                with open(fp, mode) as f:
                    for chunk in resp.iter_content(1 << 16):
                        f.write(chunk)
            size = os.path.getsize(fp)
            if total and size < total:
                raise RuntimeError(f"未下完 {size}/{total}")
            return size
        except Exception as e:
            print(f"  ! 第{attempt}次失败 {r['id']}: {e}", flush=True)
            time.sleep(2 * attempt)
    return -1

def main():
    ok, fail, skip = 0, [], 0
    total_bytes = 0
    t0 = time.time()
    for i, r in enumerate(rows, 1):
        fp = target(r)
        if os.path.exists(fp) and os.path.getsize(fp) > 200_000:
            skip += 1
            total_bytes += os.path.getsize(fp)
            print(f"[{i}/{len(rows)}] 跳过已存在 {os.path.basename(fp)}", flush=True)
            continue
        print(f"[{i}/{len(rows)}] 下载 {r['date']} {r['dur_s']}s {r['desc'][:30]}", flush=True)
        sz = download(r)
        if sz > 0:
            ok += 1; total_bytes += sz
            print(f"    -> {sz/1e6:.1f}MB", flush=True)
        else:
            fail.append(r["id"])
            print("    -> 失败", flush=True)
    print(f"\n完成: 新下载 {ok}, 跳过 {skip}, 失败 {len(fail)} {fail}", flush=True)
    print(f"总大小 {total_bytes/1e9:.2f}GB, 耗时 {time.time()-t0:.0f}s", flush=True)

if __name__ == "__main__":
    main()
