#!/usr/bin/env python3
"""Cek ritme terbit artikel (dan jadwal mendatang) di TSC dan Kendangsari Hospital."""
import base64, importlib.util, json, re, time, urllib.error, urllib.request
from collections import Counter
from datetime import date, datetime, timedelta, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
WIB = timezone(timedelta(hours=7))


def klien(nama):
    spec = importlib.util.spec_from_file_location("cfg", f"{WS}/cfg_{nama}.py")
    m = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(m)
    c = m.CFG
    return c["domain"], base64.b64encode(f"{c['user']}:{c['pass']}".encode()).decode()


def ambil(dom, auth, path):
    h = {"Authorization": f"Basic {auth}", "User-Agent": "Mozilla/5.0"}
    r = urllib.request.Request(f"https://{dom}{path}", headers=h)
    for i in range(4):
        try:
            with urllib.request.urlopen(r, timeout=120) as x:
                return json.loads(x.read())
        except urllib.error.HTTPError as e:
            if e.code in (429, 404):
                time.sleep(4)
                continue
            return {"err": e.code}
        except Exception:
            time.sleep(4)
    return {}


for nama, label in (("tsc", "The Skin Code Clinic"), ("rsia", "Kendangsari Hospital")):
    try:
        dom, auth = klien(nama)
    except Exception as e:
        print(f"\n=== {label}: cfg_{nama}.py gagal dibaca: {str(e)[:60]}")
        continue
    print(f"\n=== {label} ({dom}) ===")
    posts = ambil(dom, auth, "/wp-json/wp/v2/posts?per_page=100&status=publish&orderby=date&order=desc&_fields=id,date,slug")
    if isinstance(posts, list):
        per_hari = Counter(p["date"][:10] for p in posts)
        print(f"   artikel publish (100 terbaru), 14 hari terakhir:")
        for t in sorted(per_hari, reverse=True)[:14]:
            tanda = "  ⚠ lebih dari satu" if per_hari[t] > 1 else ""
            print(f"      {t}: {per_hari[t]} artikel{tanda}")
    else:
        print("   gagal ambil daftar artikel:", str(posts)[:80])

    fut = ambil(dom, auth, "/wp-json/wp/v2/posts?per_page=50&status=future&orderby=date&order=asc&_fields=id,date,slug,title")
    if isinstance(fut, list):
        print(f"   artikel terjadwal (menunggu tayang): {len(fut)}")
        for x in fut[:10]:
            print(f"      {x['date'][:16]} | #{x['id']} | {x['slug'][:50]}")
    dr = ambil(dom, auth, "/wp-json/wp/v2/posts?per_page=50&status=draft&orderby=date&order=desc&_fields=id,date,slug")
    if isinstance(dr, list):
        print(f"   draf: {len(dr)}")
