#!/usr/bin/env python3
"""Cek semua jadwal Repliz: pastikan jadwal tipe video punya video & URL-nya live."""
import json, sys, time, concurrent.futures
import urllib.request, urllib.error
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/repliz_audit_dump.json"

def fetch_all():
    c = get_client()
    r = c.get_schedules(page=1, limit=100)
    total = r["totalDocs"]
    pages = (total + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        rr = c.get_schedules(page=p, limit=100)
        docs.extend(rr["docs"])
        if p % 25 == 0:
            print(f"  ...{len(docs)}/{total}", flush=True)
    print(f"✅ total fetched: {len(docs)}")
    with open(OUT, "w") as f:
        json.dump(docs, f)
    return docs

def check_url(url, timeout=20):
    """HEAD dulu, fallback GET range — fbcdn sering blok HEAD."""
    req = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "Mozilla/5.0", "Range": "bytes=0-1023"})
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.status
    except urllib.error.HTTPError as e:
        if e.code in (403, 405):
            # fallback: GET range
            try:
                req2 = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0", "Range": "bytes=0-1023"})
                with urllib.request.urlopen(req2, timeout=timeout) as resp2:
                    return resp2.status
            except urllib.error.HTTPError as e2:
                return e2.code
            except Exception:
                return "ERR-GET"
        return e.code
    except Exception as e:
        return f"ERR-{type(e).__name__}"

def main():
    if len(sys.argv) > 1 and sys.argv[1] == "fetch":
        docs = fetch_all()
    else:
        with open(OUT) as f:
            docs = json.load(f)
        print(f"📂 loaded {len(docs)} jadwal dari dump")

    # Klasifikasi
    video_scheds = [d for d in docs if d.get("type") == "video" or any(m.get("type") == "video" for m in (d.get("medias") or []))]
    print(f"🎬 jadwal tipe video: {len(video_scheds)} dari {len(docs)} total")

    # 1) Jadwal video TANPA media video
    no_video = []
    for d in video_scheds:
        medias = d.get("medias") or []
        has_video = any(m.get("type") == "video" and m.get("url") for m in medias)
        if not has_video:
            no_video.append(d)
    print(f"⚠️  jadwal video TANPA video: {len(no_video)}")

    # 2) Cek URL semua media video (unik)
    urls = {}
    for d in video_scheds:
        for m in (d.get("medias") or []):
            if m.get("type") == "video" and m.get("url"):
                urls.setdefault(m["url"], []).append(d["id"])
    print(f"🔗 URL video unik: {len(urls)} — mulai cek HTTP...")

    results = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=12) as ex:
        fut = {ex.submit(check_url, u): u for u in urls}
        done = 0
        for f in concurrent.futures.as_completed(fut):
            u = fut[f]
            try:
                results[u] = f.result()
            except Exception as e:
                results[u] = f"ERR-{e}"
            done += 1
            if done % 100 == 0:
                print(f"  ...{done}/{len(urls)}", flush=True)

    bad = {u: s for u, s in results.items() if s != 200}
    print(f"\n✅ URL OK (200): {len(results) - len(bad)}/{len(results)}")
    print(f"❌ URL bermasalah: {len(bad)}")

    # Simpan laporan
    report = {
        "total_jadwal": len(docs),
        "total_video_jadwal": len(video_scheds),
        "video_tanpa_video": [{"id": d["id"], "title": d.get("title",""), "type": d.get("type"), "status": d.get("status"), "scheduleAt": d.get("scheduleAt"), "account": (d.get("account") or {}).get("name","")} for d in no_video],
        "url_bad": [{"url": u, "status": s, "schedule_ids": urls[u][:5], "total_jadwal_pakai": len(urls[u])} for u, s in bad.items()],
        "url_ok_count": len(results) - len(bad),
    }
    with open("/home/mantapman/.hermes/profiles/atun/workspace/repliz_audit_report.json", "w") as f:
        json.dump(report, f, indent=1, ensure_ascii=False)
    print("\n📄 laporan: repliz_audit_report.json")

    # Ringkas akun untuk yang error
    if bad:
        acc_cnt = {}
        for u in bad:
            for sid in urls[u][:1]:
                d = next((x for x in docs if x["id"] == sid), None)
                if d:
                    nm = (d.get("account") or {}).get("name", "?")
                    acc_cnt[nm] = acc_cnt.get(nm, 0) + 1
        print("per-akun (jadwal dgn URL error):", acc_cnt)

if __name__ == "__main__":
    main()
