# -*- coding: utf-8 -*-
"""下载评论里的图片，并汇总评论统计"""
import glob, json, os, requests

ROOT = r"D:\Deepseek\douyin_fengdaquan"
RAW = os.path.join(ROOT, "comments_raw")
IMG = os.path.join(ROOT, "comments_images")
os.makedirs(IMG, exist_ok=True)

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/"}


def to_url(x):
    """兼容三种形态：字符串 / {url_list:[...]} / 嵌套 list"""
    if x is None:
        return None
    if isinstance(x, str):
        return x if x.startswith("http") else None
    if isinstance(x, dict):
        for u in x.get("url_list") or []:
            if isinstance(u, str) and u.startswith("http"):
                return u
        return to_url(x.get("origin_url"))
    if isinstance(x, (list, tuple)):
        for i in x:
            u = to_url(i)
            if u:
                return u
    return None


def main():
    total_c, total_img, got = 0, 0, 0
    stats = {}
    for fp in sorted(glob.glob(os.path.join(RAW, "*.json"))):
        j = json.load(open(fp, encoding="utf-8"))
        aweme = j["aweme_id"]
        cs = j["comments"]
        imgs = [to_url(u) for c in cs for u in c["images"]]
        imgs = [u for u in imgs if u]
        total_c += len(cs); total_img += len(imgs)
        outdir = os.path.join(IMG, aweme)
        if imgs:
            os.makedirs(outdir, exist_ok=True)
        for k, url in enumerate(imgs, 1):
            ext = ".jpg" if ".jpg" in url else (".webp" if ".webp" in url else ".png")
            dst = os.path.join(outdir, f"{k:02d}{ext}")
            if os.path.exists(dst) and os.path.getsize(dst) > 1000:
                got += 1; continue
            try:
                r = requests.get(url, headers=HEAD, timeout=30)
                if r.status_code == 200 and len(r.content) > 500:
                    open(dst, "wb").write(r.content); got += 1
            except Exception as e:
                print("  图片失败", aweme, k, e)
        stats[aweme] = {"comments": len(cs), "images": len(imgs), "total": j.get("total_comments", 0)}
    json.dump(stats, open(os.path.join(ROOT, "_comments_stats.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)
    print(f"评论合计 {total_c} 条，含图片 {total_img} 张，已下载 {got} 张")


if __name__ == "__main__":
    main()
