#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""抖解 DouParse 批量下载参考实现（单文件、零第三方依赖，可直接运行）

用途
----
把一批短视频 / 图文分享链接解析成无水印直链并下载到本地目录，最后产出 failed.csv。
这个脚本同时是「给 AI 助手看的参考实现」：https://www.qimiaowan.com/agent.md
里的每一条规则，这里都有对应代码。AI 可以直接调用本脚本，也可以照它改写。

用法
----
    python douparse.py --key dpk_xxxxxxxx --links links.txt --out ./downloads
    python douparse.py --key dpk_xxxxxxxx --links 链接表.xlsx --out ./downloads
    python douparse.py --key dpk_xxxxxxxx --links links.txt --out ./downloads --audio --cover

links.txt：一行一个链接（整段分享文案也认，接口会自己从里面抠链接）
链接表.xlsx：随便哪一列，脚本会把表里所有链接抓出来（需要 openpyxl：pip install openpyxl）

设计要点（为什么这么写）
------------------------
1.「解析一条 → 立刻下载一条」。play_url 带平台签名（x-expires），几分钟就失效；
   先把几百条链接全解析再统一下载，前面那批必然 403。
2.下载必须带 Referer（按平台区分）+ 浏览器 UA，否则防盗链拦你。
3.下载完必须校验 Content-Type 和大小。防盗链被拦时平台会回 200 + HTML，
   curl 不报错，不校验就会把一张错误网页存成 .mp4。
4.限频 30 次/分钟（解析）。串行 + sleep 就够，别一上来开并发。
"""

import argparse
import csv
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request

BASE = os.environ.get("DOUPARSE_BASE", "https://www.qimiaowan.com")
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36")

# 平台 CDN → 必须带的 Referer。顺序有意义：先匹配更具体的域名。
REFERERS = (
    (("xhscdn.com", "xiaohongshu.com"), "https://www.xiaohongshu.com/"),
    (("bilivideo.com", "bilivideo.cn", "hdslb.com", "mountaintoys.cn", "bilibili.com"),
     "https://www.bilibili.com/"),
    (("kwimgs.com", "yximgs.com", "ndcimgs.com", "kwaicdn.com", "oskwai.com", "kuaishou.com"),
     "https://www.kuaishou.com/"),
    (("finder.video.qq.com", "qpic.cn", "qlogo.cn", "channels.weixin.qq.com", "video.qq.com"),
     "https://channels.weixin.qq.com/"),
    (("weibocdn.com", "video.weibo.com", "sinaimg.cn", "weibo.com"), "https://weibo.com/"),
    (("vzuu.com", "zhimg.com", "zhihu.com"), "https://www.zhihu.com/"),
    (("ixigua.com", "365yg.com", "bdxiguaimg.com"), "https://www.ixigua.com/"),
    (("bdstatic.com", "bcebos.com", "baidu.com"), "https://haokan.baidu.com/"),
    (("tiktok.com", "tiktokv.com", "tiktokcdn.com"), "https://www.tiktok.com/"),
)
DEFAULT_REFERER = "https://www.douyin.com/"

URL_RE = re.compile(r"https?://[^\s<>\"'）)]+")
OK_TYPES = ("video/", "image/", "audio/", "application/octet-stream")


def referer_for(url: str) -> str:
    """按直链域名挑 Referer——平台 CDN 的防盗链就是认这个。"""
    host = urllib.parse.urlparse(url).netloc.lower().split(":")[0]
    for suffixes, ref in REFERERS:
        if any(host == s or host.endswith("." + s) for s in suffixes):
            return ref
    return DEFAULT_REFERER


def safe_name(text: str, limit: int = 60) -> str:
    """清掉 Windows 非法字符；emoji / 书名号留着会让路径炸。"""
    text = re.sub(r'[\\/:*?"<>|\r\n\t]+', "_", text or "")
    text = re.sub(r"\s+", "_", text).strip("._")
    return text[:limit] or "video"


def read_links(path: str) -> list:
    """从 txt / csv / xlsx 里抓链接。整段分享文案也认——接口自己会抠。"""
    ext = os.path.splitext(path)[1].lower()
    texts = []

    if ext in (".xlsx", ".xlsm"):
        try:
            from openpyxl import load_workbook
        except ImportError:
            sys.exit("读 xlsx 需要 openpyxl：pip install openpyxl（或用 txt/csv）")
        wb = load_workbook(path, read_only=True, data_only=True)
        for ws in wb.worksheets:
            for row in ws.iter_rows(values_only=True):
                for cell in row:
                    if isinstance(cell, str) and cell.strip():
                        texts.append(cell.strip())
        wb.close()
    else:
        with open(path, "r", encoding="utf-8-sig", errors="replace") as f:
            texts = [ln.strip() for ln in f if ln.strip()]

    out, seen = [], set()
    for t in texts:
        hits = URL_RE.findall(t)
        item = hits[0].rstrip("，。,.") if hits else None
        # 分享文案没有裸链接（例如「复制打开抖音，看看…」）时整段丢给接口
        if not item and len(t) >= 8 and not t.startswith("#"):
            item = t
        if item and item not in seen:
            seen.add(item)
            out.append(item)
    return out


def post_json(path: str, payload: dict, key: str, timeout: int = 60) -> dict:
    req = urllib.request.Request(
        BASE + path,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": "Bearer " + key,
                 "Content-Type": "application/json",
                 "User-Agent": UA,
                 "Accept": "application/json"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8", "replace"))


def get_json(path: str, key: str, timeout: int = 30) -> dict:
    req = urllib.request.Request(
        BASE + path,
        headers={"Authorization": "Bearer " + key,
                 "User-Agent": UA,
                 "Accept": "application/json"},
    )
    with urllib.request.urlopen(req, timeout=timeout) as r:
        return json.loads(r.read().decode("utf-8", "replace"))


def download(url: str, dest: str, referer: str = "", timeout: int = 120) -> tuple:
    """下载一个直链。返回 (ok, detail)。

    校验是重点：防盗链被拦时平台回 200 + HTML，不校验就会存成假视频。
    已存在同名文件直接跳过（断点续跑）。
    """
    if os.path.exists(dest) and os.path.getsize(dest) > 10 * 1024:
        return True, "skipped_exists"

    req = urllib.request.Request(url, headers={
        "User-Agent": UA,
        "Referer": referer or referer_for(url),
        "Accept": "*/*",
    })
    tmp = dest + ".part"
    try:
        with urllib.request.urlopen(req, timeout=timeout) as r:
            ctype = (r.headers.get("Content-Type") or "").lower()
            if ctype and not any(ctype.startswith(p) for p in OK_TYPES):
                return False, f"blocked_by_cdn:content_type={ctype}"
            size = 0
            with open(tmp, "wb") as f:
                while True:
                    chunk = r.read(256 * 1024)
                    if not chunk:
                        break
                    f.write(chunk)
                    size += len(chunk)
        if size < 10 * 1024:
            os.remove(tmp)
            return False, f"blocked_by_cdn:size={size}"
        os.replace(tmp, dest)
        return True, f"{size} bytes"
    except urllib.error.HTTPError as e:
        if os.path.exists(tmp):
            os.remove(tmp)
        return False, f"blocked_by_cdn:http={e.code}"
    except Exception as e:  # noqa: BLE001  网络抖动/超时都算这一条失败，不影响后面的
        if os.path.exists(tmp):
            os.remove(tmp)
        return False, f"upstream_error:{type(e).__name__}"


def parse_one(link: str, key: str, retries: int = 2) -> dict:
    """解析一条。按 retryable / retry_after / fail_side 决定要不要重试。"""
    attempt = 0
    while True:
        attempt += 1
        try:
            j = post_json("/api/v1/parse", {"url": link}, key)
        except urllib.error.HTTPError as e:
            body = ""
            try:
                body = e.read().decode("utf-8", "replace")[:200]
            except Exception:  # noqa: BLE001
                pass
            if e.code == 429 and attempt <= retries:
                time.sleep(3 * attempt)
                continue
            if e.code in (401, 403):
                return {"ok": False, "reason": "auth_error",
                        "detail": f"HTTP {e.code}：Key 无效或无权限。{body}", "retried": attempt - 1}
            return {"ok": False, "reason": "upstream_error",
                    "detail": f"HTTP {e.code} {body}", "retried": attempt - 1}
        except Exception as e:  # noqa: BLE001
            if attempt <= retries:
                time.sleep(2 * attempt)
                continue
            return {"ok": False, "reason": "upstream_error",
                    "detail": f"{type(e).__name__}: {e}", "retried": attempt - 1}

        if j.get("code") == 0 and j.get("data"):
            return {"ok": True, "data": j["data"], "remaining": j.get("remaining"),
                    "retried": attempt - 1}

        msg = str(j.get("message") or "")
        # fail_side=link 表示作品已删/私密/不是作品链接，重试也不会变
        if j.get("fail_side") == "link":
            return {"ok": False, "reason": "deleted_or_private",
                    "detail": msg, "retried": attempt - 1}
        if j.get("retryable") and attempt <= retries:
            time.sleep(int(j.get("retry_after") or 3))
            continue
        low = msg.lower()
        reason = "invalid_link"
        if "额度" in msg or "余额" in msg or "次" in msg and "不" in msg:
            reason = "quota_exceeded"
        elif "地区" in msg or "region" in low:
            reason = "region_locked"
        return {"ok": False, "reason": reason, "detail": msg, "retried": attempt - 1}


def pick_url(d: dict, want_best: bool = True) -> str:
    """优先最高画质档位；没有档位就退 play_url。"""
    if d.get("aweme_type") == "image":
        return ""
    if want_best:
        for q in d.get("qualities") or []:
            if q.get("is_best") and q.get("url"):
                return q["url"]
    return d.get("play_url") or ""


def main() -> None:
    ap = argparse.ArgumentParser(description="抖解 DouParse 批量下载")
    ap.add_argument("--key", required=True, help="API Key（dpk_ 开头，个人中心领取）")
    ap.add_argument("--links", required=True, help="链接清单：txt / csv / xlsx")
    ap.add_argument("--out", default="./downloads", help="保存目录")
    ap.add_argument("--audio", action="store_true", help="额外下载抖音原声 MP3")
    ap.add_argument("--cover", action="store_true", help="额外下载封面图")
    ap.add_argument("--sleep", type=float, default=0.6, help="每条之间间隔秒数（限频 30/分钟）")
    ap.add_argument("--limit", type=int, default=0, help="只处理前 N 条（调试用）")
    args = ap.parse_args()

    os.makedirs(args.out, exist_ok=True)
    links = read_links(args.links)
    if args.limit:
        links = links[:args.limit]
    if not links:
        sys.exit("没有从文件里读到链接")

    # 先确认额度，别跑到一半断粮
    try:
        bal = get_json("/api/v1/balance", args.key)
    except Exception as e:  # noqa: BLE001
        sys.exit(f"余额查询失败，检查 Key 与网络：{e}")
    print(f"剩余额度：{bal.get('balance', bal)}")
    print(f"待处理 {len(links)} 条 → {os.path.abspath(args.out)}\n")

    ok_n = skip_n = 0
    failed = []

    for i, link in enumerate(links, 1):
        head = f"[{i}/{len(links)}] "
        r = parse_one(link, args.key)

        if not r["ok"]:
            failed.append([link, r["reason"], r["detail"], r["retried"]])
            print(head + f"失败 {r['reason']} · {r['detail'][:70]}")
            time.sleep(args.sleep)
            continue

        d = r["data"]
        pid = d.get("aweme_id") or f"item{i:04d}"
        plat = d.get("platform") or "douyin"
        stem = os.path.join(args.out, f"{plat}_{safe_name(pid, 32)}")
        jobs = []  # (url, 目标路径)

        if d.get("aweme_type") == "image":
            for k, img in enumerate(d.get("images") or [], 1):
                jobs.append((img, f"{stem}_{k:02d}.jpg"))
            # 实况视频与 images 按索引对应，空串表示这张没有
            for k, mv in enumerate(d.get("image_lives") or [], 1):
                if mv:
                    jobs.append((mv, f"{stem}_{k:02d}_live.mp4"))
        else:
            u = pick_url(d)
            if not u:
                failed.append([link, "invalid_link", "解析成功但没有可下载直链", r["retried"]])
                print(head + "失败 没有直链")
                time.sleep(args.sleep)
                continue
            jobs.append((u, f"{stem}.mp4"))

        if args.audio and (d.get("music") or {}).get("play_url"):
            jobs.append((d["music"]["play_url"], f"{stem}_audio.mp3"))
        if args.cover and d.get("cover"):
            jobs.append((d["cover"], f"{stem}_cover.jpg"))

        # 解析完立刻下，不攒列表（直链几分钟就过期）
        bad = []
        for url, dest in jobs:
            ok, detail = download(url, dest, referer_for(url))
            if ok and detail == "skipped_exists":
                skip_n += 1
            elif not ok:
                # 主链失败换备用链再试一次
                alt = d.get("play_url_backup") if url == d.get("play_url") else ""
                if alt:
                    ok, detail = download(alt, dest, referer_for(alt))
                if not ok:
                    bad.append((url, detail))

        if bad:
            failed.append([link, bad[0][1].split(":")[0], bad[0][1], r["retried"]])
            print(head + f"部分失败 {bad[0][1][:70]}")
        else:
            ok_n += 1
            print(head + f"完成 · {d.get('desc', '')[:34]}")

        time.sleep(args.sleep)  # 限频 30/分钟

    report = os.path.join(args.out, "failed.csv")
    if failed:
        # utf-8-sig：不加 BOM，Excel 打开中文全是乱码
        with open(report, "w", encoding="utf-8-sig", newline="") as f:
            w = csv.writer(f)
            w.writerow(["link", "reason", "detail", "retried"])
            w.writerows(failed)

    print("\n" + "=" * 52)
    print(f"成功 {ok_n} 条 · 失败 {len(failed)} 条 · 跳过已存在 {skip_n} 个文件")
    print(f"保存目录：{os.path.abspath(args.out)}")
    if failed:
        print(f"失败清单：{report}")
        reasons = {}
        for row in failed:
            reasons[row[1]] = reasons.get(row[1], 0) + 1
        print("失败归因：" + "、".join(f"{k}×{v}" for k, v in
                                  sorted(reasons.items(), key=lambda x: -x[1])))


if __name__ == "__main__":
    main()
