#!/usr/bin/env python3
"""DAS — pola terbit 60 hari terakhir + jadwal yang masih menunggu tayang (sumber pola massal)."""
import base64, importlib.util, json, time, urllib.error, urllib.request
from collections import Counter
from datetime import date, timedelta

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_das.py")
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
CFG = m.CFG
DOM = CFG["domain"]
AUTH = base64.b64encode(f"{CFG['user']}:{CFG['pass']}".encode()).decode()
UA = {"User-Agent": "Mozilla/5.0"}


def rest(path):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    r = urllib.request.Request(f"https://{DOM}{path}", headers=h)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


for st in ("publish", "future", "draft"):
    posts, page = [], 1
    while True:
        d = rest(f"/wp-json/wp/v2/posts?per_page=100&page={page}&status={st}"
                 f"&orderby=date&order=desc&_fields=id,slug,date,title,status")
        if not isinstance(d, list) or not d:
            break
        posts += d
        if len(d) < 100:
            break
        page += 1
    print(f"\n=== status {st}: {len(posts)} artikel ===")
    if st == "publish":
        per_bulan = Counter(p["date"][:7] for p in posts)
        for b in sorted(per_bulan, reverse=True)[:8]:
            print(f"   {b}: {per_bulan[b]} artikel")
        per_hari = Counter(p["date"][:10] for p in posts)
        batas = (date.today() - timedelta(days=60)).isoformat()
        baru = {t: n for t, n in per_hari.items() if t >= batas}
        print(f"   60 hari terakhir: {sum(baru.values())} artikel dalam {len(baru)} hari")
        for t in sorted(baru, reverse=True)[:14]:
            print(f"      {t}: {baru[t]} artikel")
        print("   terbit terakhir:")
        for p in posts[:6]:
            print(f"      {p['date'][:16]} #{p['id']} {p['slug'][:64]}")
    else:
        for p in posts[:10]:
            print(f"   {p['date'][:16]} #{p['id']} {p['slug'][:64]}")
