#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""更新本地全部黄果剧集

对给定 manifest 中的所有剧集：
  1) 读站点剧集页 → 当前状态（连载中/已完结）与站点集数
  2) 并发发现全部集 → 补齐本地缺失的集（已存在且时长>5s 跳过）
  3) 回写 manifest：status / episodes / last_update（含状态变化记录）

复用 hg-update-top.py 的下载核心（ptext/dfile/do_episode/collect_episodes/fetch_cover）。
"""
import re, json, time, shutil, argparse, importlib.util, html as HTML
from pathlib import Path

BASE = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查')
_spec = importlib.util.spec_from_file_location("hgut", BASE / 'scripts' / 'hg-update-top.py')
H = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(H)


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


def series_meta(sid):
    """返回 (status, site_total_episodes)；失败返回 (None, None)"""
    code, h = H.ptext(f"{H.SITE}/series/{sid}")
    if code != '200':
        return None, None
    flat = HTML.unescape(re.sub(r'\s+', ' ', re.sub(r'<[^>]+>', ' ', h)))
    m = re.search(r'(连载中|已完结)\s*·\s*(\d+)\s*集', flat)
    if not m:
        return None, None
    return m.group(1), int(m.group(2))


def local_episodes(sdir):
    out = []
    for f in sorted(sdir.glob('*.mp4')):
        mm = re.search(r'第(\d+)集', f.name)
        if not mm:
            continue
        info = H.probe(f)
        out.append({"ep": int(mm.group(1)), "file": f.name,
                    "duration": info.get('duration'), "size": info.get('size', f.stat().st_size)})
    out.sort(key=lambda x: x['ep'])
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--manifests', default=f"{BASE/'黄果剧集合集'/'manifest.json'},{BASE/'87-黄果短剧-AI题材2部'/'manifest.json'}")
    ap.add_argument('--stamp', default='20261027-all')
    ap.add_argument('--tmp', default='/tmp/hg/all')
    ap.add_argument('--skip-done', action='store_true',
                    help='只处理未完结或集数不足的（默认全量复核）')
    a = ap.parse_args()
    tmp = Path(a.tmp); tmp.mkdir(parents=True, exist_ok=True)

    summary = []
    for mp in [x.strip() for x in a.manifests.split(',') if x.strip()]:
        mpath = Path(mp)
        coll = mpath.parent
        man = json.load(open(mpath, encoding='utf-8'))
        log(f"=== {coll.name}/manifest.json：{len(man.get('series', []))} 部 ===")
        for s in man.get('series', []):
            title = s['title']
            sid = s.get('sid')
            sdir = coll / (s.get('dir') or title)
            if not sid:
                log(f"—— {title}：无 series_id（单条内容），跳过")
                summary.append({"coll": coll.name, "title": title, "skip": "无 sid"})
                continue
            sdir.mkdir(parents=True, exist_ok=True)
            before = len(list(sdir.glob('*.mp4')))
            old_status = s.get('status')
            status, site_total = series_meta(sid)
            log(f"—— {title}（{sid}）本地 {before} 集 · 站点 {site_total} 集 · {status}"
                + (f" · 原状态 {old_status}" if old_status != status else ""))
            added, failed = [], []
            try:
                eps = H.collect_episodes(sid)
            except Exception as e:
                log(f"   采集失败：{e}")
                summary.append({"coll": coll.name, "title": title, "error": str(e)})
                continue
            for ep in eps:
                try:
                    r = H.do_episode(title, sdir, ep, tmp)
                except Exception as e:
                    log(f"   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'])
            if before == 0 or not (sdir / '封面.jpg').exists():
                H.fetch_cover(sid, sdir, tmp)
            local = local_episodes(sdir)
            s['status'] = status or old_status
            s['episodes'] = local
            s['cover'] = '封面.jpg' if (sdir / '封面.jpg').exists() else s.get('cover')
            s['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": site_total, "site_status": status,
                                "status_changed_from": old_status if old_status != status else None}
            gap = (site_total or 0) - len(local)
            log(f"   ⇒ {title}: 新增 {len(added)} 集，失败 {len(failed)} 集，本地 {len(local)}/{site_total} 集"
                + (f"，仍缺 {gap} 集" if gap > 0 else "，已追平")
                + (f"，状态 {old_status} → {status}" if old_status != status else ""))
            summary.append({"coll": coll.name, "title": title, "sid": sid,
                            "local_eps": len(local), "site_eps": site_total,
                            "added": [x['ep'] for x in added], "failed": failed,
                            "status_before": old_status, "status_after": status,
                            "added_files": [{"ep": x['ep'], "file": x['file'], "duration": x.get('duration'),
                                             "size": x.get('size')} for x in added]})
            man['series_count'] = len(man['series'])
            man['episode_count'] = sum(len(x.get('episodes') or []) for x in man['series'])
            man['update_log'] = [x for x in (man.get('update_log') or []) if x.get('stamp') != a.stamp]
            man['update_log'].append({"at": time.strftime('%Y-%m-%d %H:%M:%S'), "stamp": a.stamp,
                                      "scope": "全量更新：补齐缺失集 + 刷新连载状态"})
            mpath.write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding='utf-8')
            (coll / f"全量更新报告-{a.stamp}.json").write_text(
                json.dumps({"at": time.strftime('%Y-%m-%d %H:%M:%S'), "items": summary},
                           ensure_ascii=False, indent=1), encoding='utf-8')
        log(f"=== {coll.name} 完成：{man['series_count']} 部 / {man['episode_count']} 集 ===")

    tot_add = sum(len(x.get('added') or []) for x in summary)
    tot_fail = sum(len(x.get('failed') or []) for x in summary)
    stat_chg = [x for x in summary if x.get('status_before') and x.get('status_before') != x.get('status_after')]
    log(f"\n全部完成：新增 {tot_add} 集，失败 {tot_fail} 集，状态变化 {len(stat_chg)} 部")
    for x in stat_chg:
        log(f"   状态变更：{x['title']} {x['status_before']} → {x['status_after']}")
    shutil.rmtree(tmp, ignore_errors=True)


if __name__ == '__main__':
    main()