#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场 指定片单下载器（按片名从榜单库匹配 series_id）

- 已在 84/85 目录完成的剧集用硬链接并入
- 站点页面/密钥走 VPN；分片 cdn.huangguo.video 直连
- HLS AES-128 → 本地播放列表 → ffmpeg 无损封装
"""
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'
OUT = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/86-黄果短剧-指定14部')
TMP = Path('/tmp/hg/work86')
RANK = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/黄果剧场榜单-20261012.json')
PREV_DIRS = [Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/84-黄果短剧-6小时榜前3与第8'),
             Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查/85-黄果短剧-榜单前十-三时段')]
WORKERS = 16

# 按片名指定（不含《萝莉学姐是我妈？》）
TITLES = ["大奉打更人", "少妇白洁", "我的岳母苏沛真", "母女同欢", "兄弟妈妈好好操",
          "时停手表", "有五个姐姐的我", "母衣半暖默许春期", "高冷妈妈",
          "侄媳三年没开封被叔叔操喷了", "东京牛头人", "芭蕾世家的乱伦晚宴",
          "上门瑜伽老师，当着我面骑了我老公"]

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 norm(s):
    return re.sub(r'[\s？?！!，,。.、：:·\-—_]', '', s)


def build_spec():
    d = json.load(open(RANK, encoding='utf-8'))
    lib = {}
    for k in ('6h', '24h', '7d'):
        for it in d['periods'][k]['items']:
            e = lib.setdefault(it['series_id'], {"sid": it['series_id'], "title": it['title'],
                                                 "ranks": {}, "cover": it['cover'],
                                                 "url": it['url'], "status": it['status'],
                                                 "downloads": it['downloads'], "update": it['update']})
            e['ranks'][k] = it['rank']
            e['cover'] = it['cover']
            e['status'] = it['status']
            e['downloads'] = it['downloads']
            e['update'] = it['update']
    spec, miss = [], []
    for t in TITLES:
        nt = norm(t)
        hit = next((v for v in lib.values() if norm(v['title']) == nt), None)
        if not hit:
            miss.append(t)
            continue
        spec.append(hit)
    if miss:
        log(f"⚠ 未匹配：{miss}")
    for s in spec:
        tag = '·'.join(f"{k}{s['ranks'][k]}" for k in ('6h', '24h', '7d') if k in s['ranks'])
        s['dir'] = f"{s['title']}({tag})"
    spec.sort(key=lambda x: (min(x['ranks'].values()), x['title']))
    for i, s in enumerate(spec, 1):
        s['dir'] = f"{i:02d}-{s['dir']}"
    return spec


def link_previous(spec):
    for s in spec:
        dst_dir = OUT / s['dir']
        dst_dir.mkdir(parents=True, exist_ok=True)
        src_dir = None
        for pd in PREV_DIRS:
            src_dir = next((p for p in pd.iterdir() if p.is_dir() and s['title'] in p.name), None)
            if src_dir:
                break
        if not src_dir:
            continue
        n = 0
        for f in src_dir.iterdir():
            dst = dst_dir / f.name
            if dst.exists():
                continue
            try:
                os.link(f, dst)
            except OSError:
                shutil.copy2(f, dst)
            n += 1
        if n:
            log(f"硬链接并入 {s['title']}: {n} 个文件（源 {src_dir.name}）")


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/cov86') / 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 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(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)
        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"}
    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 {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():
    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": "指定片单（13 部）",
                "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'] = []
        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()
