#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Patuhi aturan Bos: maksimal 3 artikel baru/hari, idealnya 1/hari.

Hari ini 5 artikel tayang bersamaan (6 dengan artikel profil lain) → 2 artikel terakhir
digeser ke `future`: 5 Okt 10:00 dan 6 Okt 10:00 WIB (jam 10 supaya tidak menabrak slot 08:00
milik pipeline artikel profil lain).

Pakai: python3 atur_laju_artikel.py dry | run
Verifikasi: status, tanggal, dan HTTP artikel yang tetap tayang.
"""
import base64, json, subprocess, sys, urllib.request, urllib.error

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0", "Content-Type": "application/json"}

GESER = [
    (9228, "2026-10-05T03:00:00", "branding agency surabaya, geser ke 5 Okt 10:00 WIB"),
    (9229, "2026-10-06T03:00:00", "jasa maintenance wordpress, geser ke 6 Okt 10:00 WIB"),
]
TAYANG_TETAP = [9225, 9226, 9227]


def api(path, method="GET", body=None):
    data = json.dumps(body).encode() if body is not None else None
    r = urllib.request.Request(S + path, headers=H, data=data, method=method)
    try:
        with urllib.request.urlopen(r, timeout=120) as x:
            return x.status, json.loads(x.read())
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode()[:300]


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "dry"
    print("RENCANA:")
    for pid, tgl, ket in GESER:
        print(f"  #{pid} -> future {tgl}Z ({ket})")
    print(f"  tetap tayang hari ini: {TAYANG_TETAP}")
    if mode != "run":
        return
    for pid, tgl, ket in GESER:
        st, d = api(f"/wp-json/wp/v2/posts/{pid}", "PUT",
                    {"status": "future", "date": tgl})
        if isinstance(d, dict) and d.get("id"):
            print(f"OK #{pid} status={d.get('status')} date={d.get('date')}")
        else:
            print(f"GAGAL #{pid} http={st} {str(d)[:200]}")

    print("\nVERIFIKASI:")
    for pid in [x[0] for x in GESER] + TAYANG_TETAP:
        st, d = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,status,date,link")
        if not isinstance(d, dict):
            print(f"  #{pid} error {st}"); continue
        kode = subprocess.run(["curl", "-4", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-L",
                               "--max-time", "30", d["link"] + "?cb=1"],
                              capture_output=True, text=True).stdout.strip()
        print(f"  #{pid} {d['status']:8s} {d['date']} http={kode}  {d['slug']}")


if __name__ == "__main__":
    main()
