#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""下载榜单前十目标剧集：双源（荔枝免费完整 → 黄果补差额）

用法: python3 hg-dl-top10.py [--targets /tmp/new_with_lz.json] [--only 标题1,标题2]
"""
import re, os, json, time, shutil, argparse, 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'
HG = 'https://huangguo.video'
LZ = 'https://lzweifwfs.cc'
BASE = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查')
COLL = BASE / '黄果剧集合集'
TMP = BASE / '.tmp-top10'   # 与 COLL 同分区，避免 os.replace/shutil 跨设备
WORKERS = 12


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


def curl(args, t=120):
    return subprocess.run(['curl', '-s', '--max-time', str(t), '-A', UA,
                           '--socks5-hostname', '127.0.0.1:10808'] + args, capture_output=True)


def get(url, t=40, cookie=True):
    a = ['-w', '\n#%{http_code}']
    if cookie:
        a += ['-b', 'hg_age=1']
    r = curl(a + [url], t)
    b = r.stdout.decode('utf-8', 'ignore')
    m = re.search(r'\n#(\d+)$', b)
    return (m.group(1) if m else ''), (b[:m.start()] if m else b)


def probe(p):
    if not os.path.exists(p):
        return {}
    r = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration,size',
                        '-of', 'json', p], capture_output=True)
    try:
        f = json.loads(r.stdout.decode()).get('format', {})
        return {'duration': round(float(f.get('duration', 0)), 2), 'size': int(f.get('size', 0))}
    except Exception:
        return {}


# ---------------- 黄果 ----------------
def hg_series_eps(sid):
    """返回 {ep: {vid, cid, hls, page_s}}"""
    c, h = get(f'{HG}/series/{sid}')
    if c != '200':
        return {}
    vids = []
    for m in re.finditer(r'href="/video/([a-z0-9]+)"', h):
        if m.group(1) not in vids:
            vids.append(m.group(1))

    def one(vid):
        cc, hh = get(f'{HG}/video/{vid}')
        if cc != '200' or f'/series/{sid}' not in hh:
            return None
        num = re.search(r'·\s*第(\d+)集', hh)
        cid = re.search(r'data-content-id="(\d+)"', hh)
        hls = re.search(r'data-hls="([^"]+)"', hh)
        if not (num and cid and hls):
            return None
        flat = re.sub(r'<[^>]+>', ' ', re.sub(r'<(script|style)[^>]*>.*?</\1>', '', hh, flags=re.S))
        pd = re.search(r'第\d+集\s*(\d+):(\d{2})', flat)
        page = int(pd.group(1)) * 60 + int(pd.group(2)) if pd else None
        return int(num.group(1)), {'vid': vid, 'cid': cid.group(1), 'hls': hls.group(1), 'page_s': page}

    out = {}
    with ThreadPoolExecutor(max_workers=8) as ex:
        for r in ex.map(one, vids):
            if r:
                out[r[0]] = r[1]
    return dict(sorted(out.items()))


def hg_download(hls, dest, tmpdir):
    c, master = get(HG + hls, 60)
    if c != '200':
        return False, f'manifest {c}'
    vs = [(int(m.group(1)), m.group(2)) for m in
          re.finditer(r'#EXT-X-STREAM-INF:[^\n]*BANDWIDTH=(\d+)[^\n]*\n([^\n#]+)', master)]
    if not vs:
        return False, '无变体'
    best = sorted(vs, key=lambda x: -x[0])[0][1]
    base = hls.rsplit('/', 1)[0]
    c2, pl = get(f'{HG}{base}/{best}', 60)
    if c2 != '200':
        return False, f'变体 {c2}'
    key = re.search(r'#EXT-X-KEY:[^\n]*URI="([^"]+)"', pl)
    segs = re.findall(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', pl, re.M)
    if not segs:
        return False, '无分片'
    shutil.rmtree(tmpdir, ignore_errors=True)
    os.makedirs(tmpdir, exist_ok=True)
    base_seg = f'{HG}{base}/{best}'.rsplit('/', 1)[0]
    urls = [x if x.startswith('http') else base_seg + '/' + x for x in segs]
    if key:
        ku = key.group(1)
        if not ku.startswith('http'):
            ku = HG + ku
        curl(['-o', f'{tmpdir}/key.bin', ku], 60)
        if not os.path.exists(f'{tmpdir}/key.bin'):
            return False, 'key'
    return _assemble(pl, urls, tmpdir, dest)


# ---------------- 荔枝 ----------------
def lz_manifest(lz_id, ep):
    c, h = get(f'{LZ}/drama/{lz_id}/ep-{ep}/', 40, cookie=False)
    if c != '200':
        return None
    m = re.search(r'(/api/v1/cdn/video/[^"\\ ]+manifest\.m3u8[^"\\ ]*)', h)
    return m.group(1) if m else None


def lz_download(lz_id, ep, dest, tmpdir):
    mp = lz_manifest(lz_id, ep)
    if not mp:
        return False, '无 manifest'
    c, pl = get(LZ + mp, 40, cookie=False)
    if c != '200' or '#EXTM3U' not in pl:
        return False, f'manifest {c}'
    key = re.search(r'#EXT-X-KEY:[^\n]*URI="([^"]+)"', pl)
    segs = re.findall(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', pl, re.M)
    if not segs:
        return False, '无分片'
    shutil.rmtree(tmpdir, ignore_errors=True)
    os.makedirs(tmpdir, exist_ok=True)
    if key:
        curl(['-o', f'{tmpdir}/key.bin', key.group(1)], 60)
        if not os.path.exists(f'{tmpdir}/key.bin'):
            return False, 'key'
    return _assemble(pl, segs, tmpdir, dest)


def _assemble(pl, urls, tmpdir, dest):
    def one(iu):
        i, u = iu
        fn = f'{tmpdir}/s{i:05d}.ts'
        for _ in range(4):
            r = curl(['-o', fn, '-w', '%{http_code}', u], 120)
            if r.stdout.decode().strip() == '200' and os.path.exists(fn) and os.path.getsize(fn) > 1024:
                return i, True
        return i, False

    bad = []
    with ThreadPoolExecutor(max_workers=WORKERS) as ex:
        for i, ok in ex.map(one, list(enumerate(urls))):
            if not ok:
                bad.append(i)
    if bad:
        return False, f'{len(bad)}/{len(urls)} 片失败'

    txt = re.sub(r'(#EXT-X-KEY:[^\n]*URI=")[^"]+(")', r'\1key.bin\2', pl)
    cnt = {'i': 0}

    def repl(m):
        i = cnt['i']; cnt['i'] += 1
        return f's{i:05d}.ts'

    txt = re.sub(r'^(?!#)(\S+\.ts(?:\?\S+)?)\s*$', repl, txt, flags=re.M)
    open(f'{tmpdir}/local.m3u8', 'w').write(txt)
    r = subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error', '-allowed_extensions', 'ALL',
                        '-i', f'{tmpdir}/local.m3u8', '-c', 'copy', '-bsf:a', 'aac_adtstoasc',
                        '-movflags', '+faststart', dest], capture_output=True)
    if r.returncode != 0:
        return False, 'mux ' + r.stderr.decode()[:80]
    info = probe(dest)
    if not info.get('duration'):
        return False, '产物无时长'
    shutil.rmtree(tmpdir, ignore_errors=True)
    return True, info


def safe(n):
    return re.sub(r'\s+', ' ', re.sub(r'[\\/:*?"<>|]', '-', n)).strip()[:80]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--targets', default='/tmp/new_with_lz.json')
    ap.add_argument('--only', default='')
    ap.add_argument('--stamp', default=time.strftime('%Y%m%d'))
    a = ap.parse_args()
    targets = json.load(open(a.targets, encoding='utf-8'))
    if a.only:
        want = {x.strip() for x in a.only.split(',')}
        targets = [t for t in targets if t['title'] in want]
    COLL.mkdir(parents=True, exist_ok=True)
    TMP.mkdir(parents=True, exist_ok=True)

    mpath = COLL / 'manifest.json'
    man = json.load(open(mpath, encoding='utf-8'))
    by_sid = {s['sid']: s for s in man['series']}
    report = []

    for t in targets:
        sid, title = t['sid'], t['title']
        sdir = COLL / safe(title)
        sdir.mkdir(parents=True, exist_ok=True)
        log(f"—— {title}（{sid}）站点 {t['eps']} 集 · 荔枝 {t.get('lz_id') or '无'}")

        hg = hg_series_eps(sid)
        if not hg:
            log('   ✗ 黄果取集失败')
            report.append({'title': title, 'sid': sid, 'error': 'hg eps fail'})
            continue
        lz_id = t.get('lz_id')
        lz_eps = {}
        if lz_id:
            # 找出荔枝实际可用集（页面 200 且有 manifest）
            def chk(ep):
                return ep, bool(lz_manifest(lz_id, ep))
            with ThreadPoolExecutor(max_workers=8) as ex:
                for ep, ok in ex.map(chk, list(range(1, t['eps'] + 1))):
                    if ok:
                        lz_eps[ep] = True
            log(f"   荔枝可用 {len(lz_eps)} 集")

        eps_out = []
        for ep, meta in hg.items():
            dest = sdir / f'{safe(title)}-第{ep:02d}集.mp4'
            done = probe(dest)
            if done.get('duration', 0) > 5:
                eps_out.append({'ep': ep, 'file': dest.name, **done, 'preview': False, 'source': 'cached'})
                continue
            # 黄果优先（快）；若拿到的是试看，再用荔枝换完整版
            pg = meta.get('page_s')
            ok, info = hg_download(meta['hls'], str(dest), str(TMP / f'{sid}_{ep}'))
            if ok:
                prev = bool(pg and info['duration'] < pg - 8)
                if prev and lz_id and ep in lz_eps:
                    ok2, info2 = lz_download(lz_id, ep, str(TMP / f'{sid}_{ep}.lz.mp4'), str(TMP / f'{sid}_{ep}_lz'))
                    if ok2 and pg and abs(info2['duration'] - pg) <= 6:
                        shutil.move(str(TMP / f'{sid}_{ep}.lz.mp4'), str(dest))
                        eps_out.append({'ep': ep, 'file': dest.name, **info2, 'preview': False,
                                        'source': 'lzweifwfs.cc', 'page_s': pg})
                        log(f"     EP{ep:02d} ✅ 荔枝补完整 {info2['duration']:.1f}s/{pg}s")
                        prev = None
                    elif os.path.exists(str(TMP / f'{sid}_{ep}.lz.mp4')):
                        os.remove(str(TMP / f'{sid}_{ep}.lz.mp4'))
                if prev is not None:
                    eps_out.append({'ep': ep, 'file': dest.name, **info, 'preview': prev,
                                    'source': 'huangguo.video', 'page_s': pg})
                    log(f"     EP{ep:02d} {'⚠试看' if prev else '✅'} 黄果 {info['duration']:.1f}s" +
                        (f" / 页面 {pg}s" if pg else ''))
            else:
                log(f"     EP{ep:02d} ✗ 黄果 {info}")
                eps_out.append({'ep': ep, 'file': dest.name, 'status': 'failed', 'reason': info})
            # 落盘进度
            entry = by_sid.get(sid) or {'dir': sdir.name, 'sid': sid, 'title': title}
            entry['episodes'] = [e for e in eps_out if e.get('duration')]
            entry['preview_episodes'] = sorted(e['ep'] for e in eps_out if e.get('preview'))
            entry['status'] = t.get('status')
            entry['source_rank'] = 'top10-20261110'
            if sid not in by_sid:
                man['series'].append(entry); by_sid[sid] = entry
            man['series_count'] = len(man['series'])
            man['episode_count'] = sum(len(s.get('episodes') or []) for s in man['series'])
            mpath.write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding='utf-8')
        # 封面
        cov = sdir / '封面.jpg'
        if not cov.exists():
            c, h = get(f'{HG}/series/{sid}')
            m = re.search(r'property="og:image"\s+content="([^"]+)"', h)
            if m:
                curl(['-o', str(TMP / 'c.img'), m.group(1)], 60)
                if os.path.exists(TMP / 'c.img'):
                    subprocess.run(['ffmpeg', '-y', '-hide_banner', '-loglevel', 'error',
                                    '-i', str(TMP / 'c.img'), '-vf', 'scale=480:-1', str(cov)],
                                   capture_output=True)
        good = [e for e in eps_out if e.get('duration')]
        prev = [e['ep'] for e in eps_out if e.get('preview')]
        log(f"   ⇒ {title}: {len(good)}/{t['eps']} 集，试看 {len(prev)}")
        report.append({'title': title, 'sid': sid, 'site_eps': t['eps'], 'local': len(good),
                       'preview': prev, 'eps': [{'ep': e['ep'], 'dur': e.get('duration'),
                                                 'src': e.get('source')} for e in good]})
        (COLL / f'top10下载报告-{a.stamp}.json').write_text(
            json.dumps({'at': time.strftime('%Y-%m-%d %H:%M:%S'), 'items': report},
                       ensure_ascii=False, indent=1), encoding='utf-8')

    tot = sum(r.get('local', 0) for r in report)
    log(f"\n完成：{len(report)} 部 / {tot} 集")
    shutil.rmtree(TMP, ignore_errors=True)


if __name__ == '__main__':
    main()
