#!/usr/bin/env python3
"""Pastikan artikel 08:00 WIB hari ini benar-benar tayang (#9292). Cek mulai 08:04 WIB, ulangi sampai 08:25."""
import base64, json, time, urllib.request
from datetime import datetime, timedelta, timezone

WIB = timezone(timedelta(hours=7))
A = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
H = {"Authorization": f"Basic {A}", "User-Agent": "Mozilla/5.0"}
PID = 9292

target = datetime.now(WIB).replace(hour=8, minute=4, second=0, microsecond=0)
if target > datetime.now(WIB):
    time.sleep((target - datetime.now(WIB)).total_seconds())
batas = datetime.now(WIB).replace(hour=8, minute=25, second=0, microsecond=0)
n = 0
while datetime.now(WIB) < batas:
    n += 1
    try:
        u = f"https://studiosoft.id/wp-json/wp/v2/posts/{PID}?context=edit&_fields=id,status,date,slug"
        d = json.loads(urllib.request.urlopen(urllib.request.Request(u, headers=H), timeout=90).read())
        print(f"{datetime.now(WIB):%H:%M} cek {n}: status={d['status']} date={d['date']}", flush=True)
        if d["status"] == "publish":
            print("TAYANG", flush=True)
            raise SystemExit(0)
    except SystemExit:
        raise
    except Exception as e:
        print(f"{datetime.now(WIB):%H:%M} cek {n}: gagal {type(e).__name__}", flush=True)
    # kunjungi halaman supaya wp-cron terpicu
    try:
        urllib.request.urlopen(urllib.request.Request("https://studiosoft.id/", headers={"User-Agent": "Mozilla/5.0"}), timeout=60).read(100)
    except Exception:
        pass
    time.sleep(90)
print("BELUM TAYANG sampai 08:25 WIB", flush=True)
raise SystemExit(2)
