#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场 AI 题材 2 部下载器（《性爱机器人》连续剧 2 集 + 《社会你豆包姐》片段）

- 站点页面/密钥走 VPN(socks5h)；分片 cdn.huangguo.video 直连
- HLS AES-128 → 本地播放列表 → ffmpeg 无损封装
- 复现自 hg-fetch-titles.py 的同一链路
"""
import os, re, json, time, shutil, subprocess
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
SITE = 'https://huangguo.video'
OUT = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/87-黄果短剧-AI题材2部')
TMP = Path('/tmp/hg/work87')
WORKERS = 16

# 1) 连续剧：性爱机器人（series bcphy3ay，2 集）
SERIES = [{
    "dir": "01-性爱机器人",
    "title": "性爱机器人",
    "sid": "bcphy3ay",
    "url": f"{SITE}/series/bcphy3ay",
    "cover": f"{SITE}/uploads/content/series/85/cover.webp?v=1787502565",
    "type": "连续剧",
    "note": "全站唯一「机器人」题材；标签 都市；@墨白",
}]
# 2) 单条片段：社会你豆包姐（video 1cx4eu8y）
STANDALONE = [{
    "dir": "02-社会你豆包姐",
    "title": "社会你豆包姐",
    "vid": "1cx4eu8y",
    "url": f"{SITE}/video/1cx4eu8y",
    "cover": f"{SITE}/uploads/content/video/2173/cover/01.jpg?v=1789498797",
    "type": "片段",
    "note": "二次元玩梗昵称，非字节「豆包」AI；@51z",
}]

CLEAN_ENV = {k: v for k, v in os.environ.items()
             if k.lower() not in ('all_proxy', 'http_proxy', 'https_proxy', 'ftp_proxy', 'no_proxy')}


def curl(a, t=90):
    return subprocess.run(['curl', '-s', '-A', UA, '--max-time', str(t)] + a, capture_output=True, env=CLEAN_ENV)


def ptext(url, t=90):
    r = curl(['--socks5-hostname', '127.0.0.1:10808', '-w', '\n#CODE:%{http_code}', url], t)
    b = r.stdout.decode('utf-8', 'ignore')
    m = re.search(r'\n#CODE:(\d+)$', b)
    return (m.group(1) if m else ''), (b[:m.start()] if m else b)


def pfile(url, dest, t=90):
    r = curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest), '-w', '%{http_code}', url], t)
    return r.stdout.decode().strip()


def dfile(url, dest, t=90):
    r = curl(['--noproxy', '*', '-o', str(dest), '-w', '%{http_code}', url], t)
    out = r.stdout.decode().strip()
    if out != '200':
        out = curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest), '-w', '%{http_code}', url], t).stdout.decode().strip()
    return out


def log(m):
    print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)


def parse_playlist(text):
    variants = [(int(m.group(1)), m.group(2)) for m in
                re.finditer(r'#EXT-X-STREAM-INF:[^\n]*BANDWIDTH=(\d+)[^\n]*\n([^\n#]+)', text)]
    key = re.search(r'#EXT-X-KEY:[^\n]*URI="([^"]+)"(?:[^\n]*IV=(0x[0-9a-fA-F]+))?', text)
    segs = re.findall(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', text, re.M)
    return variants, (key.group(1) if key else None), (key.group(2) if (key and key.group(2)) else None), segs


def probe(mp4):
    if not mp4.exists():
        return {}
    r = subprocess.run(['ffprobe', '-v', 'error', '-show_entries',
                        'format=duration,size:stream=codec_type,codec_name,width,height',
                        '-of', 'json', str(mp4)], capture_output=True)
    try:
        j = json.loads(r.stdout.decode())
    except Exception:
        return {}
    f = j.get('format', {})
    v = next((x for x in j.get('streams', []) if x.get('codec_type') == 'video'), {})
    a = next((x for x in j.get('streams', []) if x.get('codec_type') == 'audio'), None)
    return {"duration": round(float(f.get('duration', 0)), 2), "size": int(f.get('size', 0)),
            "vcodec": v.get('codec_name'), "w": v.get('width'), "h": v.get('height'),
            "acodec": (a or {}).get('codec_name')}


def fetch_episode(ep):
    code, master = ptext(f"{SITE}{ep['hls']}")
    if code != '200':
        raise RuntimeError(f"master {code}")
    variants, _, _, _ = parse_playlist(master)
    if not variants:
        raise RuntimeError("无清晰度")
    best = sorted(variants, key=lambda x: -x[0])[0][1]
    vurl = f"{SITE}{ep['hls']}".rsplit('/', 1)[0] + '/' + best
    c2, pl = ptext(vurl)
    if c2 != '200':
        raise RuntimeError(f"变体 {c2}")
    _, key_uri, iv, segs = parse_playlist(pl)
    base = vurl.rsplit('/', 1)[0]
    abs_segs = [x if x.startswith('http') else base + '/' + x for x in segs]
    key_url = key_uri if (key_uri or '').startswith('http') else (SITE + key_uri if key_uri else None)
    return pl, abs_segs, key_url, iv, best


def collect_episodes(s):
    """从剧集页取 /video/ 链接，并回验该视频页确实属于本剧（防相关推荐污染）"""
    code, html = ptext(f"{SITE}/series/{s['sid']}")
    if code != '200':
        raise RuntimeError(f"剧集页 {code}")
    vids, seen = [], set()
    for m in re.finditer(r'href="/video/([a-z0-9]+)"', html):
        if m.group(1) not in seen:
            seen.add(m.group(1))
            vids.append(m.group(1))
    eps = []
    for vid in vids:
        c, h = ptext(f"{SITE}/video/{vid}")
        if c != '200':
            continue
        if f'/series/{s["sid"]}' not in h:      # 回验归属
            continue
        cid = re.search(r'data-content-id="(\d+)"', h)
        hls = re.search(r'data-hls="([^"]+)"', h)
        num = re.search(r'·\s*第(\d+)集', h)
        if not (cid and hls and num):
            continue
        eps.append({"vid": vid, "ep": int(num.group(1)), "cid": cid.group(1), "hls": hls.group(1),
                    "url": f"{SITE}/video/{vid}"})
    eps.sort(key=lambda x: x['ep'])
    return eps


def do_item(title, sdir, item, out_name):
    tag = f"{title} {out_name}"
    out_mp4 = sdir / out_name
    if out_mp4.exists() and probe(out_mp4).get('duration', 0) > 5:
        return {"file": out_mp4.name, "status": "skipped"}
    seg_dir = TMP / re.sub(r'[^\w\-]', '_', f"{title}_{out_name}")
    shutil.rmtree(seg_dir, ignore_errors=True)
    seg_dir.mkdir(parents=True, exist_ok=True)
    t0 = time.time()
    pl, seg_urls, key_url, iv, variant = fetch_episode(item)
    exp = round(sum(float(x) for x in re.findall(r'#EXTINF:([\d.]+)', pl)), 2)

    def one(iu):
        i, u = iu
        name = f"seg_{i:05d}.ts"
        dest = seg_dir / name
        res = dfile(u, dest)
        return i, name, (res == '200' and dest.exists() and dest.stat().st_size > 0)

    mapping, failed = {}, []
    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
        for i, name, ok in ex.map(one, list(enumerate(seg_urls))):
            (mapping.__setitem__(i, name) if ok else failed.append(i))
    if failed:
        log(f"{tag} 重试 {len(failed)} 片（刷新 token）")
        pl2, seg_urls2, key_url, iv, variant = fetch_episode(item)
        if len(seg_urls2) == len(seg_urls):
            with ThreadPoolExecutor(max_workers=WORKERS) as ex:
                for i, name, ok in ex.map(one, [(i, seg_urls2[i]) for i in failed]):
                    if ok:
                        mapping[i] = name
        failed = [i for i in failed if i not in mapping]
    if failed:
        return {"file": out_name, "status": "failed", "reason": f"{len(failed)} 片缺失"}
    key_name = 'key.bin'
    if key_url:
        if pfile(key_url, seg_dir / key_name) != '200':
            return {"file": out_name, "status": "failed", "reason": "key"}
    else:
        key_name = None
    txt = re.sub(r'(#EXT-X-KEY:[^\n]*URI=")[^"]+(")', lambda m: m.group(1) + str(key_name) + m.group(2), pl)
    cnt = {'i': 0}

    def repl(m):
        i = cnt['i']
        cnt['i'] += 1
        return mapping.get(i, m.group(0))

    txt = re.sub(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', repl, txt, flags=re.M)
    lp = seg_dir / 'local.m3u8'
    lp.write_text(txt, encoding='utf-8')
    r = subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-allowed_extensions', 'ALL',
                        '-i', str(lp), '-c', 'copy', '-bsf:a', 'aac_adtstoasc', '-movflags', '+faststart',
                        str(out_mp4)], capture_output=True)
    info = probe(out_mp4)
    got = info.get('duration', 0)
    if r.returncode != 0 or got < max(5, exp - 3):
        if r.returncode != 0:
            log(f"{tag} ⚠ mux 失败 {r.stderr.decode('utf-8','ignore')[:150]}")
            return {"file": out_name, "status": "failed", "reason": "mux"}
    shutil.rmtree(seg_dir, ignore_errors=True)
    dt = time.time() - t0
    log(f"{tag} ✅ {info.get('duration')}s {info.get('size',0)/1048576:.1f}MB {info.get('w')}x{info.get('h')} 用时{dt:.0f}s")
    return {"file": out_name, "status": "ok", "duration": info.get('duration'), "size": info.get('size'),
            "w": info.get('w'), "h": info.get('h'), "vcodec": info.get('vcodec'), "acodec": info.get('acodec'),
            "cid": item['cid'], "vid": item['vid'], "url": item['url'], "variant": variant,
            "elapsed": round(dt, 1), "expected_duration": exp}


def fetch_cover(item, sdir):
    jpg = sdir / '封面.jpg'
    if jpg.exists():
        return
    tmp = TMP / 'cov'
    tmp.mkdir(parents=True, exist_ok=True)
    raw = tmp / f"{item.get('sid') or item.get('vid')}.img"
    if pfile(item['cover'], raw) == '200' and raw.stat().st_size > 1000:
        subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(raw),
                        '-vf', 'scale=480:-1', str(jpg)], capture_output=True)
        log(f"封面 OK {item['title']}")


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    TMP.mkdir(parents=True, exist_ok=True)
    manifest = {"platform": "黄果剧场 huangguo.video",
                "scope": "AI/机器人题材 2 部（《性爱机器人》连续剧 2 集 + 《社会你豆包姐》片段）",
                "built_at": time.strftime('%Y-%m-%d %H:%M:%S'), "series": []}

    for s in SERIES:
        sdir = OUT / s['dir']
        sdir.mkdir(parents=True, exist_ok=True)
        fetch_cover(s, sdir)
        entry = {k: s.get(k) for k in ('dir', 'sid', 'title', 'url', 'type', 'note')}
        entry['episodes'] = []
        try:
            eps = collect_episodes(s)
        except Exception as e:
            log(f"{s['title']} 采集失败 {e}")
            entry['error'] = str(e)
            manifest['series'].append(entry)
            continue
        log(f"{s['title']}: {len(eps)} 集 EP{[e['ep'] for e in eps]}")
        for ep in eps:
            try:
                entry['episodes'].append(do_item(s['title'], sdir, ep, f"{s['title']}-第{ep['ep']:02d}集.mp4"))
            except Exception as e:
                log(f"{s['title']} EP{ep['ep']} 异常 {e}")
                entry['episodes'].append({"file": f"{s['title']}-第{ep['ep']:02d}集.mp4", "status": "error", "err": str(e)})
            (OUT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')
        manifest['series'].append(entry)
        (OUT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')

    for v in STANDALONE:
        sdir = OUT / v['dir']
        sdir.mkdir(parents=True, exist_ok=True)
        fetch_cover(v, sdir)
        entry = {k: v.get(k) for k in ('dir', 'vid', 'title', 'url', 'type', 'note')}
        entry['episodes'] = []
        try:
            c, h = ptext(f"{SITE}/video/{v['vid']}")
            cid = re.search(r'data-content-id="(\d+)"', h)
            hls = re.search(r'data-hls="([^"]+)"', h)
            if c != '200' or not (cid and hls):
                raise RuntimeError(f"视频页 {c} cid={bool(cid)} hls={bool(hls)}")
            item = {"vid": v['vid'], "ep": 1, "cid": cid.group(1), "hls": hls.group(1), "url": v['url']}
            log(f"{v['title']}: 单条 {v['type']} cid={item['cid']}")
            entry['episodes'].append(do_item(v['title'], sdir, item, f"{v['title']}.mp4"))
        except Exception as e:
            log(f"{v['title']} 异常 {e}")
            entry['episodes'].append({"file": f"{v['title']}.mp4", "status": "error", "err": str(e)})
        manifest['series'].append(entry)
        (OUT / 'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')

    ok = sum(1 for s in manifest['series'] for e in s['episodes'] if e.get('status') in ('ok', 'skipped'))
    tot = sum(len(s['episodes']) for s in manifest['series'])
    log(f"完成：{ok}/{tot} 个文件，{len(manifest['series'])} 部")
    shutil.rmtree(TMP, ignore_errors=True)


if __name__ == '__main__':
    main()
