#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场 热播排行榜 6h/24h/7d 三时段「前十」全量下载（去重 20 部）

- 已在 84 目录下完成的剧集用硬链接并入，不重复下载、不额外占盘
- 站点页面/密钥走 VPN(socks5h://127.0.0.1:10808)；分片 cdn.huangguo.video 直连
- HLS AES-128 → 本地播放列表 → 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-黄果平台调查/85-黄果短剧-榜单前十-三时段')
PREV = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/84-黄果短剧-6小时榜前3与第8')
TMP = Path('/tmp/hg/work85')
SPEC = Path('/tmp/hg/spec85.json')
RANK = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/黄果剧场榜单-20261012.json')
WORKERS = 16

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


def ptext(url, timeout=90):
    r = curl(['--socks5-hostname', '127.0.0.1:10808', '-w', '\n#CODE:%{http_code}', url], timeout)
    body = r.stdout.decode('utf-8', 'ignore')
    m = re.search(r'\n#CODE:(\d+)$', body)
    code = m.group(1) if m else ''
    if m:
        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}', url], timeout)
    return r.stdout.decode().strip()


def dfile(url, dest, timeout=90):
    r = curl(['--noproxy', '*', '-o', str(dest), '-w', '%{http_code}', url], timeout)
    out = r.stdout.decode().strip()
    if out != '200':
        r2 = curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest), '-w', '%{http_code}', url], timeout)
        out = r2.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((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 build_spec():
    d = json.load(open(RANK, encoding='utf-8'))
    agg = {}
    for k in ('6h', '24h', '7d'):
        for it in d['periods'][k]['items']:
            if it['rank'] > 10:
                continue
            e = agg.setdefault(it['series_id'], {"sid": it['series_id'], "title": it['title'],
                                                 "ranks": {}, "cover": it['cover'],
                                                 "url": it['url'], "status": it['status'],
                                                 "downloads": it['downloads']})
            e['ranks'][k] = it['rank']
            e['cover'] = it['cover']
            e['status'] = it['status']
    rows = sorted(agg.values(), key=lambda x: (min(x['ranks'].values()), x['title']))
    spec = []
    for i, r in enumerate(rows, 1):
        tag = '·'.join(f"{k}{r['ranks'][k]}" for k in ('6h', '24h', '7d') if k in r['ranks'])
        cid = re.search(r'/series/([a-z0-9]+)', r['url']).group(1)
        spec.append({"dir": f"{i:02d}-{r['title']}({tag})", "sid": cid, "title": r['title'],
                     "ranks": r['ranks'], "cover": r['cover'], "status": r['status'],
                     "downloads": r['downloads']})
    SPEC.write_text(json.dumps(spec, ensure_ascii=False, indent=1), encoding='utf-8')
    return spec


def link_previous(spec):
    """把 84 目录已下好的剧集硬链接过来"""
    moved = 0
    for s in spec:
        src_dir = next((p for p in PREV.iterdir() if p.is_dir() and s['title'] in p.name), None)
        if not src_dir:
            continue
        dst_dir = OUT / s['dir']
        dst_dir.mkdir(parents=True, exist_ok=True)
        for f in src_dir.iterdir():
            dst = dst_dir / f.name
            if dst.exists():
                continue
            try:
                os.link(f, dst)
                moved += 1
            except OSError:
                shutil.copy2(f, dst)
                moved += 1
        log(f"硬链接并入 {s['title']}: {len(list(dst_dir.glob('*.mp4')))} 集")
    return moved


def fetch_covers(spec):
    for s in spec:
        dst_dir = OUT / s['dir']
        dst_dir.mkdir(parents=True, exist_ok=True)
        jpg = dst_dir / '封面.jpg'
        if jpg.exists():
            continue
        webp = Path('/tmp/hg/cov85') / f"{s['sid']}.webp"
        webp.parent.mkdir(parents=True, exist_ok=True)
        if pfile(s['cover'], webp) == '200' and webp.stat().st_size > 1000:
            subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-i', str(webp),
                            '-vf', 'scale=480:-1', str(jpg)], capture_output=True)
            log(f"封面 OK {s['title']}")


# ---------------- 下载阶段 ----------------
def collect_episodes(s):
    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
        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 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)
    if not segs:
        raise RuntimeError("无分片")
    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 do_episode(title, sdir, ep):
    tag = f"{title} EP{ep['ep']:02d}"
    out_mp4 = sdir / f"{title}-第{ep['ep']:02d}集.mp4"
    if out_mp4.exists() and probe(out_mp4).get('duration', 0) > 5:
        return {"ep": ep['ep'], "file": out_mp4.name, "status": "skipped"}
    seg_dir = TMP / f"{title}_EP{ep['ep']:02d}"
    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(ep)
    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)
        ok = res == '200' and dest.exists() and dest.stat().st_size > 0
        return i, name, ok

    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(ep)
        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 {"ep": ep['ep'], "status": "failed", "reason": f"{len(failed)} 片缺失"}
    key_name = 'key.bin'
    if key_url:
        if pfile(key_url, seg_dir / key_name) != '200':
            return {"ep": ep['ep'], "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):
        log(f"{tag} ⚠ rc={r.returncode} {got}/{exp} {r.stderr.decode('utf-8','ignore')[:150]}")
        if r.returncode != 0:
            return {"ep": ep['ep'], "status": "failed", "reason": "mux"}
    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')} 用时{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,
            "seg_mb": round(seg_bytes / 1048576, 1), "elapsed": round(dt, 1)}


def main():
    OUT.mkdir(parents=True, exist_ok=True)
    TMP.mkdir(parents=True, exist_ok=True)
    spec = build_spec()
    log(f"三时段前十去重：{len(spec)} 部")
    link_previous(spec)
    fetch_covers(spec)
    manifest = {"platform": "黄果剧场 huangguo.video",
                "scope": "热播排行榜 6小时/24小时/7天 三时段前十（去重）",
                "built_at": time.strftime('%Y-%m-%d %H:%M:%S'), "series": []}
    for s in spec:
        sdir = OUT / s['dir']
        sdir.mkdir(parents=True, exist_ok=True)
        entry = {k: s[k] for k in ('dir', 'sid', 'title', 'ranks', 'status', 'downloads')}
        entry['url'] = f"{SITE}/series/{s['sid']}"
        entry['episodes'] = []
        have = len(list(sdir.glob('*.mp4')))
        if have >= 1:
            log(f"{s['title']}: 已有 {have} 集")
        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_episode(s['title'], sdir, ep))
            except Exception as e:
                log(f"{s['title']} EP{ep['ep']} 异常 {e}")
                entry['episodes'].append({"ep": ep['ep'], "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')
    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'])} 部")


if __name__ == '__main__':
    main()
