#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""按缺口清单增量更新：荔枝免费完整优先 → 黄果补差额"""
import re, os, json, time, shutil, importlib.util, argparse
from pathlib import Path

BASE = Path('/home/zyw/Downloads/dl-hub/83-黄果平台调查')
_s = importlib.util.spec_from_file_location('hg', BASE / 'scripts' / 'hg-dl-top10.py')
H = importlib.util.module_from_spec(_s); _s.loader.exec_module(H)
COLL, TMP = H.COLL, Path('/tmp/hg/upd')


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--targets', default='/tmp/update_targets.json')
    a = ap.parse_args()
    targets = json.load(open(a.targets, encoding='utf-8'))
    TMP.mkdir(parents=True, exist_ok=True)
    mpath = COLL / 'manifest.json'
    man = json.load(open(mpath, encoding='utf-8'))
    by_sid = {s['sid']: s for s in man['series']}
    rep = []

    for t in targets:
        sid, title = t['sid'], t['title']
        ent = by_sid.get(sid)
        if not ent:
            H.log(f"⚠ 未入库：{title}"); continue
        sdir = COLL / ent['dir']
        H.log(f"—— {title}：需 {len(t['need'])} 集（{t['local']}→{t['site']}）")
        hg = H.hg_series_eps(sid)
        lz_id = t.get('lz_id')
        added, prev, fail = [], [], []
        for ep in t['need']:
            meta = hg.get(ep)
            if not meta:
                H.log(f"   EP{ep:02d} ✗ 黄果无此集"); fail.append(ep); continue
            dest = sdir / f"{H.safe(title)}-第{ep:02d}集.mp4"
            pg = meta.get('page_s')
            ok = False
            if lz_id:
                ok, info = H.lz_download(lz_id, ep, str(dest), str(TMP / f"{sid}_{ep}"))
                if ok and pg and abs(info['duration'] - pg) > 6:
                    ok = False
                    if os.path.exists(dest): os.remove(dest)
            if ok:
                added.append(ep); H.log(f"   EP{ep:02d} ✅ 荔枝 {info['duration']:.0f}s")
            else:
                ok2, info2 = H.hg_download(meta['hls'], str(dest), str(TMP / f"{sid}_{ep}"))
                if ok2:
                    isprev = bool(pg and info2['duration'] < pg - 8)
                    added.append(ep)
                    if isprev: prev.append(ep)
                    H.log(f"   EP{ep:02d} {'⚠试看' if isprev else '✅'} 黄果 {info2['duration']:.0f}s/{pg}s")
                else:
                    H.log(f"   EP{ep:02d} ✗ {info2}"); fail.append(ep)
            # 增量落盘
            eps = []
            for f in sorted(os.listdir(sdir)):
                if not f.endswith('.mp4'): continue
                m = re.search(r'第(\d+)集', f)
                if not m: continue
                pr = H.probe(str(sdir / f))
                eps.append({'ep': int(m.group(1)), 'file': f, **pr})
            eps.sort(key=lambda x: x['ep'])
            ent['episodes'] = eps
            ent['preview_episodes'] = sorted(set(ent.get('preview_episodes') or []) | set(prev))
            man['episode_count'] = sum(len(s.get('episodes') or []) for s in man['series'])
            man['series_count'] = len(man['series'])
            mpath.write_text(json.dumps(man, ensure_ascii=False, indent=1), encoding='utf-8')
        rep.append({'title': title, 'sid': sid, 'added': added, 'preview': prev, 'failed': fail})
        H.log(f"   ⇒ {title}: +{len(added)} 集，试看 {len(prev)}，失败 {len(fail)}")

    tot = sum(len(x['added']) for x in rep)
    H.log(f"\n完成：{len(rep)} 部，新增 {tot} 集")
    (COLL / '增量更新报告-20261110.json').write_text(
        json.dumps({'at': time.strftime('%Y-%m-%d %H:%M:%S'), 'items': rep},
                   ensure_ascii=False, indent=1), encoding='utf-8')
    shutil.rmtree(TMP, ignore_errors=True)


if __name__ == '__main__':
    main()
