#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场（huangguo.video）6 小时榜「前三 + 第 8 名」四部短剧全量下载器

链路：站点页面/密钥 → VPN(socks5h://127.0.0.1:10808)；视频分片(cdn.huangguo.video) → 直连。
分片为 HLS AES-128 加密 TS，落地为本地播放列表交由 ffmpeg 解密 + 无损封装 MP4。
"""
import os, re, sys, 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-黄果平台调查/84-黄果短剧-6小时榜前3与第8')
TMP = Path('/tmp/hg/work')
WORKERS = 16

SERIES = [
    ("01-网调我的冰山妈妈", "f6ol95s2"),
    ("02-爱情公寓", "jn8d88p6"),
    ("03-母上攻略", "fvg2fdwj"),
    ("08-重生之征服郭伯母", "cdzp3l7"),
]

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(args, timeout=90):
    cmd = ['curl', '-s', '-A', UA, '--max-time', str(timeout)] + args
    return subprocess.run(cmd, capture_output=True, env=CLEAN_ENV)


def ptext(url, timeout=90):
    """经 VPN 取文本"""
    r = curl(['--socks5-hostname', '127.0.0.1:10808', '-w', '\n#CODE:%{http_code}', url], timeout)
    body = r.stdout.decode('utf-8', 'ignore')
    code = ''
    m = re.search(r'\n#CODE:(\d+)$', body)
    if m:
        code = m.group(1)
        body = body[:m.start()]
    return code, body


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


def dfile(url, dest, timeout=90):
    """直连 CDN 下载；失败回退 VPN"""
    r = curl(['--noproxy', '*', '-o', str(dest), '-w', '%{http_code} %{size_download}', url], timeout)
    out = r.stdout.decode().strip()
    ok = out.startswith('200')
    if not ok:
        r2 = curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest),
                   '-w', '%{http_code} %{size_download}', url], timeout)
        out = r2.stdout.decode().strip()
    return out


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


def parse_playlist(text):
    """返回 (variants, key_uri, iv, segments, map_uri)"""
    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)
    key_uri = key.group(1) if key else None
    iv = key.group(2) if (key and key.group(2)) else None
    segs = re.findall(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', text, re.M)
    mp = re.search(r'#EXT-X-MAP:URI="([^"]+)"', text)
    return variants, key_uri, iv, segs, (mp.group(1) if mp else None)


def pick_best(variants):
    if not variants:
        return None
    return sorted(variants, key=lambda x: -x[0])[0][1]


def download_segments(seg_urls, seg_dir, ep_tag):
    """并行下载分片，返回 {index: filename} 及失败列表"""
    seg_dir.mkdir(parents=True, exist_ok=True)
    mapping, failed = {}, []

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

    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
        for i, name, ok, res in ex.map(one, list(enumerate(seg_urls))):
            if ok:
                mapping[i] = name
            else:
                failed.append((i, seg_urls[i], res))
    return mapping, failed


def build_local_playlist(src_playlist, seg_map, key_name, iv, seg_dir):
    txt = src_playlist
    # 密钥改本地
    txt = re.sub(r'(#EXT-X-KEY:[^\n]*URI=")[^"]+(")', lambda m: m.group(1) + key_name + m.group(2), txt)
    # 分片 URL → 本地文件名（按出现顺序对应 seg_NNNNN.ts）
    counter = {'i': 0}

    def repl(m):
        idx = counter['i']
        counter['i'] += 1
        return seg_map.get(idx, m.group(0))

    txt = re.sub(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', repl, txt, flags=re.M)
    p = seg_dir / 'local.m3u8'
    p.write_text(txt, encoding='utf-8')
    return p


def mux(playlist, out_mp4):
    r = subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error',
                        '-allowed_extensions', 'ALL', '-i', str(playlist),
                        '-c', 'copy', '-bsf:a', 'aac_adtstoasc', '-movflags', '+faststart',
                        str(out_mp4)], capture_output=True)
    return r.returncode, r.stderr.decode('utf-8', 'ignore')


def probe(mp4):
    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((s for s in j.get('streams', []) if s.get('codec_type') == 'video'), {})
    a = next((s for s in j.get('streams', []) if s.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 expected_duration(playlist_text):
    return round(sum(float(x) for x in re.findall(r'#EXTINF:([\d.]+)', playlist_text)), 2)


def collect_episodes(series_name, sid, manifest):
    """抓剧集主页 → 每个 vid 的页 → 集号/cid/hls"""
    code, html = ptext(f"{SITE}/series/{sid}")
    if code != '200':
        raise RuntimeError(f"剧集页失败 {sid}: {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':
            log(f"  跳过 {vid} (HTTP {c})")
            continue
        cid = re.search(r'data-content-id="(\d+)"', h)
        hls = re.search(r'data-hls="([^"]+)"', h)
        num = re.search(r'·\s*第(\d+)集', h)
        dur = re.search(r'<span class="badge">(\d+:\d+)</span>', h)
        if not (cid and hls and num):
            log(f"  跳过 {vid} (字段缺失)")
            continue
        eps.append({"vid": vid, "ep": int(num.group(1)), "cid": cid.group(1),
                    "hls": hls.group(1), "badge_dur": dur.group(1) if dur else None,
                    "url": f"{SITE}/video/{vid}"})
    eps.sort(key=lambda x: x['ep'])
    log(f"{series_name}: {len(eps)} 集 → EP{[e['ep'] for e in eps]}")
    return eps


def fetch_episode(ep, seg_dir):
    """返回 (playlist_text, seg_urls, key_url, iv, best_variant_url)"""
    code, master = ptext(f"{SITE}{ep['hls']}")
    if code != '200':
        raise RuntimeError(f"master 失败 {code}")
    variants, _, _, _, _ = parse_playlist(master)
    best = pick_best(variants)
    if not best:
        raise RuntimeError("无可用清晰度")
    base = f"{SITE}{ep['hls']}"
    vurl = base.rsplit('/', 1)[0] + '/' + best
    c2, pl = ptext(vurl)
    if c2 != '200':
        raise RuntimeError(f"变体播放列表失败 {c2}")
    _, key_uri, iv, segs, map_uri = parse_playlist(pl)
    if not segs:
        raise RuntimeError("播放列表无分片")
    # 分片 URL 补全为绝对地址
    abs_segs = []
    for s in segs:
        if s.startswith('http'):
            abs_segs.append(s)
        else:
            abs_segs.append(vurl.rsplit('/', 1)[0] + '/' + s)
    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 do_episode(series_name, sdir, ep, manifest_series):
    tag = f"{series_name} EP{ep['ep']:02d}"
    seg_dir = TMP / f"{series_name}_EP{ep['ep']:02d}"
    if seg_dir.exists():
        shutil.rmtree(seg_dir)
    seg_dir.mkdir(parents=True, exist_ok=True)
    out_mp4 = sdir / f"{series_name.split('-', 1)[1]}-第{ep['ep']:02d}集.mp4"
    if out_mp4.exists() and probe(out_mp4).get('duration', 0) > 5:
        log(f"{tag} 已存在，跳过")
        return {"ep": ep['ep'], "file": out_mp4.name, "status": "skipped"}

    t0 = time.time()
    pl, seg_urls, key_url, iv, variant = fetch_episode(ep, seg_dir)
    exp = expected_duration(pl)
    mapping, failed = download_segments(seg_urls, seg_dir, tag)
    if failed:
        log(f"{tag} 首次失败 {len(failed)} 片，刷新 token 重试…")
        time.sleep(1)
        pl2, seg_urls2, key_url2, iv, variant = fetch_episode(ep, seg_dir)
        if len(seg_urls2) == len(seg_urls):
            for i, _u, _r in failed:
                res = dfile(seg_urls2[i], seg_dir / f"seg_{i:05d}.ts")
                if res.startswith('200'):
                    mapping[i] = f"seg_{i:05d}.ts"
        failed = [(i, u, r) for i, u, r in failed if i not in mapping]
    if failed:
        log(f"{tag} ⚠ {len(failed)} 片仍失败，跳过该集")
        return {"ep": ep['ep'], "status": "failed", "failed": len(failed)}

    # 密钥
    key_name = 'key.bin'
    if key_url:
        res = pfile(key_url, seg_dir / key_name)
        if not res.startswith('200'):
            log(f"{tag} ⚠ 密钥获取失败 {res}")
            return {"ep": ep['ep'], "status": "failed", "reason": "key"}
    else:
        key_name = None
    local = build_local_playlist(pl, mapping, key_name, iv, seg_dir)
    rc, err = mux(local, out_mp4)
    info = probe(out_mp4)
    got = info.get('duration', 0)
    if rc != 0 or got < max(5, exp - 3):
        log(f"{tag} ⚠ 封装异常 rc={rc} 时长 {got}/{exp} {err[:200]}")
        if rc != 0:
            return {"ep": ep['ep'], "status": "failed", "reason": "mux", "err": err[:300]}
    seg_bytes = sum(f.stat().st_size for f in seg_dir.glob('*.ts'))
    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 "
        f"{info.get('w')}x{info.get('h')} {info.get('vcodec')}/{info.get('acodec')} "
        f"分片{seg_bytes/1048576:.1f}MB 用时{dt:.0f}s")
    return {"ep": ep['ep'], "file": out_mp4.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": ep['cid'], "vid": ep['vid'],
            "url": ep['url'], "variant": variant, "badge_dur": ep.get('badge_dur'),
            "elapsed": round(dt, 1)}


def main():
    only = sys.argv[1] if len(sys.argv) > 1 else None
    OUT.mkdir(parents=True, exist_ok=True)
    TMP.mkdir(parents=True, exist_ok=True)
    manifest = {"platform": "黄果剧场 huangguo.video", "source": "6小时榜 前三 + 第8名",
                "fetched_at": time.strftime('%Y-%m-%d %H:%M:%S'), "series": []}
    for series_name, sid in SERIES:
        if only and only not in series_name:
            continue
        sdir = OUT / series_name
        sdir.mkdir(parents=True, exist_ok=True)
        entry = {"name": series_name, "series_id": sid, "url": f"{SITE}/series/{sid}", "episodes": []}
        try:
            eps = collect_episodes(series_name, sid, manifest)
        except Exception as e:
            log(f"{series_name} 采集失败: {e}")
            entry['error'] = str(e)
            manifest['series'].append(entry)
            continue
        for ep in eps:
            try:
                r = do_episode(series_name, sdir, ep, entry)
            except Exception as e:
                log(f"{series_name} EP{ep['ep']} 异常: {e}")
                r = {"ep": ep['ep'], "status": "error", "err": str(e)}
            entry['episodes'].append(r)
            (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')
    (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} 集")


if __name__ == '__main__':
    main()
