#!/usr/bin/env python3
"""Audit jadwal pending 8 hari ke depan: cek semua URL media masih hidup (200)."""
import sys, collections
from datetime import datetime, timedelta, timezone
import urllib.request, ssl

from repliz_client import get_client

c = get_client()
docs, page = [], 1
while True:
    r = c.get_schedules(page, 100)
    docs += r.get("docs", [])
    if not r.get("hasNextPage"):
        break
    page += 1

WIB = timezone(timedelta(hours=7))
now = datetime.now(WIB)
batas = now + timedelta(days=8)

pend = []
for d in docs:
    if str(d.get("status")) not in ("pending", "scheduled", "processing", "draft"):
        continue
    try:
        t = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        continue
    if now - timedelta(hours=2) <= t <= batas:
        pend.append((t, d))

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE


def cek(url):
    try:
        req = urllib.request.Request(url, method="GET", headers={"User-Agent": "Mozilla/5.0", "Range": "bytes=0-2047"})
        with urllib.request.urlopen(req, timeout=25, context=ctx) as resp:
            return resp.status, len(resp.read())
    except urllib.error.HTTPError as e:
        return e.code, 0
    except Exception as e:
        return type(e).__name__, 0


print(f"jadwal pending 8 hari: {len(pend)}")
cache, masalah = {}, []
for t, d in sorted(pend, key=lambda x: x[0]):
    acc = (d.get("account") or {}).get("name", "?")
    urls = [m.get("url") for m in (d.get("medias") or []) if m.get("url")]
    hasil = []
    for u in urls:
        if u not in cache:
            cache[u] = cek(u)
        kode, n = cache[u]
        hasil.append((u.split("/")[-1][:38], kode, n))
    bad = [h for h in hasil if h[1] != 200 and h[1] != 206]
    if bad:
        masalah.append((t, acc, d.get("type"), str(d.get("title"))[:45], bad))

print(f"url unik dicek: {len(cache)} | jadwal bermasalah: {len(masalah)}")
for t, acc, typ, judul, bad in masalah:
    print(f"  {t:%d %b %H:%M} {acc} [{typ}] {judul}")
    for nama, kode, n in bad[:3]:
        print(f"     - {nama} → {kode} ({n}B)")

# jadwal tanpa media (teks murni) tetap aman
kosong = [1 for t, d in pend if not (d.get("medias") or [])]
print("jadwal tanpa media (teks):", len(kosong))
print("\nRINGKAS per akun (pending):")
for k, v in collections.Counter((d.get("account") or {}).get("name", "?") for t, d in pend).most_common():
    print(" ", v, k)
