#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场 单部直下：series/jqg3tsph（萝莉学姐是我妈？ 24h榜30 · 已完结10集）

- 与 hg-fetch-titles.py（13 部批次）并行运行：独立 TMP、独立 manifest 文件
- 不写 86/manifest.json（由最终合并步处理）
- 站点页面/密钥走 VPN；分片 cdn.huangguo.video 直连
"""
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'
SID = 'jqg3tsph'
TITLE = '萝莉学姐是我妈？'
DIRNAME = '14-萝莉学姐是我妈？(24h30)'
OUT = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/86-黄果短剧-指定14部')
SUDIR = OUT / DIRNAME
TMP = Path('/tmp/hg/work-loli')
MANIFEST = TMP / 'manifest.json'
COVER = 'https://huangguo.video/uploads/content/series/758/cover.webp?v=1791650904'
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(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 collect_episodes():
    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))
    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 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 do_episode(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"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"{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):
        if r.returncode != 0:
            log(f"{tag} ⚠ mux 失败 {r.stderr.decode('utf-8','ignore')[:150]}")
            return {"ep": ep['ep'], "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 {"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, "elapsed": round(dt, 1)}


def main():
    SUDIR.mkdir(parents=True, exist_ok=True)
    TMP.mkdir(parents=True, exist_ok=True)
    jpg = SUDIR / '封面.jpg'
    if not jpg.exists():
        webp = TMP / 'cover.webp'
        if pfile(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 {TITLE}")
    eps = collect_episodes()
    log(f"{TITLE}: {len(eps)} 集 EP{[e['ep'] for e in eps]}")
    entry = {"dir": DIRNAME, "sid": SID, "title": TITLE, "ranks": {"24h": 30},
             "status": "已完结", "downloads": 14, "note": "用户指定直下（series/jqg3tsph）",
             "url": f"{SITE}/series/{SID}", "episodes": []}
    manifest = {"platform": "黄果剧场 huangguo.video", "scope": f"单部直下 {TITLE}",
                "built_at": time.strftime('%Y-%m-%d %H:%M:%S'), "series": [entry]}
    for ep in eps:
        try:
            entry['episodes'].append(do_episode(SUDIR, ep))
        except Exception as e:
            log(f"{TITLE} EP{ep['ep']} 异常 {e}")
            entry['episodes'].append({"ep": ep['ep'], "status": "error", "err": str(e)})
        MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=1), encoding='utf-8')
    ok = sum(1 for e in entry['episodes'] if e.get('status') in ('ok', 'skipped'))
    log(f"完成：{ok}/{len(eps)} 集")


if __name__ == '__main__':
    main()
