#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场：按榜单前 N 名增量下载 / 追更到合集

- 输入：榜单 JSON（默认 黄果剧场榜单-<date>.json），取三时段各前 N 名并集
- 行为：已存在的集跳过（时长>5s 视为完整）；缺的集下载；新剧建目录
- 落盘：<合集>/<剧名>/剧名-第NN集.mp4，封面 封面.jpg
- 合并：更新 <合集>/manifest.json（保留历史名次 rank_history、追加新集、记录 last_update）
- 站点页走 VPN；分片 CDN 直连，失败回退 VPN
"""
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'
SITE = 'https://huangguo.video'
BASE = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查')
WORKERS = 16
DISC_WORKERS = 8   # 并发发现剧集的 worker 数（VPN 页面请求）

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=120):
    r = curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest), '-w', '%{http_code}', url], t)
    return r.stdout.decode().strip()


DIRECT_OK = {'v': None}   # 直连 CDN 是否可用：None=未探测 True=可用 False=已废弃


def dfile(url, dest, t=120):
    """先快速试探直连（8s 上限），失败则本次运行内全程走 VPN。

    ⚠️ 2026-10-27 实测：`cdn.huangguo.video` 的 DNS 被污染到不可达地址（IPv6 假地址），
    直连会黑洞到 max-time 才失败——若每个分片都先试直连，单集要多等几分钟。
    """
    if DIRECT_OK['v'] is not False:
        out = curl(['--noproxy', '*', '-o', str(dest), '-w', '%{http_code}', url], 8).stdout.decode().strip()
        if out == '200':
            DIRECT_OK['v'] = True
            return out
        DIRECT_OK['v'] = False
    return curl(['--socks5-hostname', '127.0.0.1:10808', '-o', str(dest), '-w', '%{http_code}', url], t).stdout.decode().strip()


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(sid):
    code, html = ptext(f"{SITE}/series/{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))
    def one(vid):
        c, h = ptext(f"{SITE}/video/{vid}")
        if c != '200' or f'/series/{sid}' not in h:
            return None
        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):
            return None
        return {"vid": vid, "ep": int(num.group(1)), "cid": cid.group(1), "hls": hls.group(1),
                "url": f"{SITE}/video/{vid}"}

    # 并发发现（VPN 单次往返较慢，串行 15 集要几分钟）
    with ThreadPoolExecutor(max_workers=DISC_WORKERS) as ex:
        eps = [x for x in ex.map(one, vids) if x]
    eps.sort(key=lambda x: x['ep'])
    return eps


def do_episode(title, sdir, ep, tmp):
    out_name = f"{title}-第{ep['ep']:02d}集.mp4"
    out_mp4 = sdir / out_name
    if out_mp4.exists() and probe(out_mp4).get('duration', 0) > 5:
        return {"ep": ep['ep'], "file": out_name, "status": "skipped"}
    seg_dir = tmp / re.sub(r'[^\w\-]', '_', 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)
        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"{title} EP{ep['ep']:02d} 重试 {len(failed)} 片")
        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'], "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 {"ep": ep['ep'], "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"{title} EP{ep['ep']:02d} ⚠ mux 失败 {r.stderr.decode('utf-8','ignore')[:120]}")
            return {"ep": ep['ep'], "file": out_name, "status": "failed", "reason": "mux"}
    shutil.rmtree(seg_dir, ignore_errors=True)
    dt = time.time() - t0
    log(f"  {title} EP{ep['ep']:02d} ✅ {info.get('duration')}s {info.get('size',0)/1048576:.1f}MB 用时{dt:.0f}s")
    return {"ep": ep['ep'], "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": ep['cid'], "vid": ep['vid'], "url": ep['url'], "variant": variant,
            "elapsed": round(dt, 1)}


def fetch_cover(sid, sdir, tmp):
    jpg = sdir / '封面.jpg'
    if jpg.exists() and jpg.stat().st_size > 1000:
        return True
    code, h = ptext(f"{SITE}/series/{sid}")
    m = re.search(r'property="og:image"\s+content="([^"]+)"', h) or re.search(r'content="([^"]+)"\s+property="og:image"', h)
    if not m:
        return False
    raw = tmp / f"cov_{sid}.img"
    if pfile(m.group(1), 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)
        return True
    return False


def build_targets(rank_json, periods, n):
    d = json.load(open(rank_json, encoding='utf-8'))
    t = {}
    for k in periods:
        for i in d['periods'][k]['items'][:n]:
            if i['kind'] != 'series' or not i['series_id']:
                log(f"⚠ 跳过非剧集条目：{i['title']}（{i['kind']}）")
                continue
            e = t.setdefault(i['series_id'], {"sid": i['series_id'], "title": i['title'],
                                              "ranks": {}, "downloads": None, "status": None})
            e['ranks'][k] = i['rank']
            e['downloads'] = i['downloads']
            e['status'] = i['status']
    return sorted(t.values(), key=lambda x: (min(x['ranks'].values()), x['title']))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--rank-file', default=str(BASE / '黄果剧场榜单-20261027.json'))
    ap.add_argument('--coll', default=str(BASE / '黄果剧集合集'))
    ap.add_argument('--n', type=int, default=5)
    ap.add_argument('--periods', default='6h,24h,7d')
    ap.add_argument('--stamp', default='20261027', help='本次更新标记（写进 manifest/报告）')
    ap.add_argument('--tmp', default='/tmp/hg/top5')
    a = ap.parse_args()
    periods = [p.strip() for p in a.periods.split(',') if p.strip()]
    coll = Path(a.coll)
    tmp = Path(a.tmp)
    tmp.mkdir(parents=True, exist_ok=True)
    coll.mkdir(parents=True, exist_ok=True)

    targets = build_targets(Path(a.rank_file), periods, a.n)
    log(f"目标 {len(targets)} 部（{'+'.join(periods)} 各前 {a.n} 名，按剧去重）")

    mpath = coll / 'manifest.json'
    man = json.load(open(mpath, encoding='utf-8')) if mpath.exists() else \
        {"platform": "黄果剧场 huangguo.video", "series": []}
    by_sid = {s['sid']: s for s in man['series']}

    # 本次运行的 update_log 条目只记一次（同 stamp 覆盖，避免每部重复追加）
    run_entry = {"at": time.strftime('%Y-%m-%d %H:%M:%S'), "stamp": a.stamp,
                 "scope": f"{'+'.join(periods)} 各前 {a.n}", "source": Path(a.rank_file).name}
    man['update_log'] = [x for x in (man.get('update_log') or []) if x.get('stamp') != a.stamp]
    man['update_log'].append(run_entry)

    report = []
    for t in targets:
        title, sid = t['title'], t['sid']
        sdir = coll / title
        sdir.mkdir(parents=True, exist_ok=True)
        log(f"—— {title}（{sid}）本地已有 " +
            f"{len(list(sdir.glob('*.mp4')))} 集")
        entry = by_sid.get(sid)
        added, failed = [], []
        try:
            eps = collect_episodes(sid)
        except Exception as e:
            log(f"  {title} 采集失败：{e}")
            report.append({"title": title, "sid": sid, "error": str(e)})
            continue
        log(f"  站点共 {len(eps)} 集 EP{[e['ep'] for e in eps]}")
        for ep in eps:
            try:
                r = do_episode(title, sdir, ep, tmp)
            except Exception as e:
                log(f"  {title} EP{ep['ep']:02d} 异常 {e}")
                failed.append(ep['ep'])
                continue
            if r['status'] == 'ok':
                added.append(r)
            elif r['status'] == 'failed':
                failed.append(ep['ep'])
        fetch_cover(sid, sdir, tmp)

        # 汇总本地实际文件（以磁盘为准）
        local = []
        for f in sorted(sdir.glob('*.mp4')):
            mm = re.search(r'第(\d+)集', f.name)
            if not mm:
                continue
            info = probe(f)
            local.append({"ep": int(mm.group(1)), "file": f.name,
                          "duration": info.get('duration', (entry or {}).get('episodes', [{}])[0].get('duration')),
                          "size": info.get('size', f.stat().st_size)})
        local.sort(key=lambda x: x['ep'])

        if entry:
            old_ranks = entry.get('ranks') or {}
            if old_ranks:
                entry.setdefault('rank_history', {}).setdefault('2026-10-12', old_ranks)
            entry.setdefault('rank_history', {})[a.stamp] = t['ranks']
            entry['ranks'] = t['ranks'] or old_ranks
            entry['downloads'] = t['downloads']
            entry['status'] = t['status'] or entry.get('status')
            entry['episodes'] = local
            entry['cover'] = '封面.jpg'
            entry['last_update'] = {"at": time.strftime('%Y-%m-%d %H:%M:%S'), "stamp": a.stamp,
                                    "added_eps": [x['ep'] for x in added], "failed_eps": failed,
                                    "site_eps": len(eps)}
        else:
            entry = {"dir": title, "sid": sid, "title": title, "ranks": t['ranks'],
                     "downloads": t['downloads'], "status": t['status'], "cover": '封面.jpg',
                     "episodes": local,
                     "last_update": {"at": time.strftime('%Y-%m-%d %H:%M:%S'), "stamp": a.stamp,
                                     "added_eps": [x['ep'] for x in added], "failed_eps": failed,
                                     "site_eps": len(eps), "new_series": True}}
            man['series'].append(entry)
            by_sid[sid] = entry
        log(f"  ⇒ {title}: 新增 {len(added)} 集，失败 {len(failed)} 集，本地合计 {len(local)} 集")
        report.append({"title": title, "sid": sid, "ranks": t['ranks'], "site_eps": len(eps),
                       "local_eps": len(local), "added": [x['ep'] for x in added],
                       "added_files": [{"ep": x['ep'], "file": x['file'], "duration": x.get('duration'),
                                        "size": x.get('size')} for x in added],
                       "failed": failed})
        # 每部写完即落盘，避免中断丢进度
        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')
        (coll / f"TOP{a.n}更新报告-{a.stamp}.json").write_text(
            json.dumps({"at": time.strftime('%Y-%m-%d %H:%M:%S'), "scope": f"{'+'.join(periods)} 各前 {a.n}",
                        "source_rank": Path(a.rank_file).name, "items": report}, ensure_ascii=False, indent=1),
            encoding='utf-8')

    tot_add = sum(len(r.get('added') or []) for r in report)
    tot_fail = sum(len(r.get('failed') or []) for r in report)
    log(f"\n完成：{len(report)} 部处理，新增 {tot_add} 集，失败 {tot_fail} 集")
    log(f"manifest: {mpath}（{man['series_count']} 部 / {man['episode_count']} 集）")
    shutil.rmtree(tmp, ignore_errors=True)


if __name__ == '__main__':
    main()
