#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""黄果剧场热播排行榜抓取器（三时段：6 小时 / 24 小时 / 7 天）

输出：<OUT>/黄果剧场榜单-<YYYYMMDD>.json / .csv / .md
- 站点页走 VPN(socks5h)，直连不可达（海外站 + Cloudflare）
- 榜单条目含两类：连续剧(/series/<sid>) 与 独立短片(/video/<vid>)
- 2026-10-27 起榜单页改版：不再展示分级(限制级/裸露/安全)、封面路径 /uploads/content/ → /uploads/lib/、
  下载数出现 K/M 缩写（旧版是纯数字），故本脚本按新结构解析并归一化
"""
import re, csv, json, time, html as H, argparse, subprocess
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-黄果平台调查')
# 2026-11-10 改版：榜单从「6h/24h/7d 时段」改为 5 个主题榜
PERIODS = [('hot', '热播榜', f'{SITE}/ranking'),
           ('new', '新剧榜', f'{SITE}/ranking/new'),
           ('rising', '飙升榜', f'{SITE}/ranking/rising'),
           ('good', '好评榜', f'{SITE}/ranking/good'),
           ('download', '下载榜', f'{SITE}/ranking/download')]


def fetch(url, t=60):
    r = subprocess.run(['curl', '-s', '-A', UA, '--max-time', str(t),
                        '--socks5-hostname', '127.0.0.1:10808', url], capture_output=True)
    return r.stdout.decode('utf-8', 'ignore')


def parse_downloads(s):
    """'1.5K' → 1500 ; '937' → 937 ; '2.1M' → 2100000 ; '' → None"""
    if not s:
        return None
    m = re.match(r'^\s*([\d.]+)\s*([KkMm]?)\s*$', s)
    if not m:
        return None
    v = float(m.group(1))
    mult = {'': 1, 'k': 1000, 'K': 1000, 'm': 1000000, 'M': 1000000}[m.group(2)]
    return int(round(v * mult))


def parse_ranking(page_html):
    items = []
    blocks = re.findall(r'<li class="ranking-item.*?</li>', page_html, flags=re.S)
    for b in blocks:
        rk = re.search(r'aria-label="第 (\d+) 名"', b)
        if not rk:
            continue
        rank = int(rk.group(1))
        ser = re.search(r'href="/series/([a-z0-9]+)"', b)
        vid = re.search(r'href="/video/([a-z0-9]+)"', b)
        kind = 'series' if ser else ('video' if vid else None)
        sid, vvid = (ser.group(1) if ser else None), (vid.group(1) if vid else None)
        title = re.search(r'font-card-title[^>]*>([^<]*)<', b)
        title = H.unescape(title.group(1)).strip() if title else None
        cover = re.search(r'<img[^>]+src="([^"]+)"', b)
        cover = cover.group(1) if cover else None
        if cover and cover.startswith('/'):
            cover = SITE + cover
        pill = re.search(r'cover-pill-text[^>]*>([^<]*)<', b)
        pill = H.unescape(pill.group(1)).strip() if pill else None
        meta = re.search(r'text-\[11px\][^>]*>([^<]*)<', b)
        meta = H.unescape(re.sub(r'\s+', ' ', meta.group(1))).strip() if meta else ''
        # meta_raw 形如 '连续剧 · 连载中 · 1.5K 次下载' 或 '短片 · 10:19 · 16 次下载'
        parts = [p.strip() for p in meta.split('·')] if meta else []
        mtype = parts[0] if parts else None
        status = None
        duration = None
        dl = None
        for p in parts[1:]:
            if '次下载' in p:
                dl = parse_downloads(p.replace('次下载', '').strip())
            elif re.match(r'^\d+:\d+$', p):
                duration = p
            elif p in ('连载中', '已完结'):
                status = p
        if duration and mtype == '短片':
            status = None
        # pill 对连续剧是进度('更新至第N集')，对短片是时长
        update = pill if (pill and ('更新' in pill or '全' in pill or '第' in pill)) else None
        if duration is None and pill and re.match(r'^\d+:\d+$', pill):
            duration = pill
        items.append({"rank": rank, "kind": kind, "title": title,
                      "series_id": sid, "video_id": vvid,
                      "url": f"{SITE}/{'series/' + sid if sid else 'video/' + (vvid or '')}",
                      "cover": cover, "rating": None,
                      "update": update, "duration": duration,
                      "type": mtype, "status": status, "downloads": dl,
                      "meta_raw": meta})
    items.sort(key=lambda x: x['rank'])
    return items


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--boards', default='hot,new,rising,good,download', help='要抓的榜单')
    ap.add_argument('--date', default=time.strftime('%Y%m%d'), help='输出文件日期戳')
    ap.add_argument('--out', default=str(BASE))
    a = ap.parse_args()
    out = Path(a.out)

    data = {"fetched_at": time.strftime('%Y-%m-%d %H:%M:%S CST'),
            "egress": "socks5h://127.0.0.1:10808 (VPN)",
            "source": f"{SITE}/ranking",
            "site_rev": "2026-10-27 版（无分级字段；封面 /uploads/lib/；下载数带 K/M）",
            "periods": {}}
    for key, label, url in PERIODS:
        h = fetch(url)
        items = parse_ranking(h)
        data['periods'][key] = {"label": label, "url": url, "count": len(items), "items": items}
        nt = len({i['title'] for i in items})
        print(f"[{key}] {len(items)} 条（去重剧名 {nt}）")

    base = out / f"黄果剧场榜单-{a.date}"
    (base.with_suffix('.json')).write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding='utf-8')

    with open(base.with_suffix('.csv'), 'w', newline='', encoding='utf-8-sig') as f:
        w = csv.writer(f)
        w.writerow(['时段', '排名', '剧名', '类型', '系列ID', '视频ID', '连载进度', '时长', '状态', '下载数', '链接'])
        for key, label, _ in PERIODS:
            for i in data['periods'][key]['items']:
                w.writerow([label, i['rank'], i['title'], i['type'], i['series_id'] or '',
                            i['video_id'] or '', i['update'] or '', i['duration'] or '',
                            i['status'] or '', i['downloads'] if i['downloads'] is not None else '', i['url']])

    L = [f"# 黄果剧场（huangguo.video）热播排行榜 — {a.date}", "",
         f"- **抓取时间**：{data['fetched_at']}（本机时间）",
         f"- **出口方式**：VPN（`{data['egress']}`）",
         f"- **榜单入口**：<{SITE}/ranking>（6 小时 / 24 小时 / 7 天）",
         f"- **命中条数**：" + " · ".join(f"{v['label']} {v['count']} 条" for v in data['periods'].values())]
    all_t = {i['title'] for v in data['periods'].values() for i in v['items']}
    tri = set.intersection(*[{i['title'] for i in v['items']} for v in data['periods'].values()])
    L += [f"- **三榜并集**：**{len(all_t)} 部**；同时出现在三榜：**{len(tri)} 部**", ""]
    for key, label, url in PERIODS:
        v = data['periods'][key]
        L += [f"## {label}榜（{v['count']} 条）", "",
              "| 排名 | 剧名 | 类型 | 进度/时长 | 状态 | 下载数 | 链接 |", "|---:|---|---|---|---|---:|---|"]
        for i in v['items']:
            prog = i['update'] or i['duration'] or ''
            dl = i['downloads'] if i['downloads'] is not None else ''
            link = i['url'].replace(SITE + '/', '')
            L.append(f"| {i['rank']} | {i['title']} | {i['type'] or ''} | {prog} | {i['status'] or ''} | {dl} | [{link}]({i['url']}) |")
        L += ["", f"*源：`{url}`*", ""]
    (base.with_suffix('.md')).write_text('\n'.join(L) + '\n', encoding='utf-8')
    print(f"\n已写出：\n  {base}.json\n  {base}.csv\n  {base}.md")


if __name__ == '__main__':
    main()