#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tayangkan SEKARANG dua artikel pilar (properti #9186, manufaktur #9187).

Alasan: carousel IG SS tayang 08:30 WIB hari ini harus menautkan URL yang SUDAH hidup.
Verifikasi: status=publish + HTTP 200 dari luar (curl -4).
"""
import base64, json, subprocess, time, urllib.request, urllib.error
from datetime import datetime, timedelta, timezone

S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
WIB = timezone(timedelta(hours=7))
IDS = [9186, 9187]


def api(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", "User-Agent": "Mozilla/5.0"}
    body = json.dumps(data).encode() if data is not None else None
    if data is not None:
        h["Content-Type"] = "application/json"
    r = urllib.request.Request(S + path, data=body, headers=h, method=method)
    for _ in range(3):
        try:
            with urllib.request.urlopen(r, timeout=180) as x:
                return x.status, json.loads(x.read())
        except urllib.error.HTTPError as e:
            return e.code, e.read().decode()[:200]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


now = datetime.now(WIB).replace(microsecond=0)
for pid in IDS:
    st, p = api(f"/wp-json/wp/v2/posts/{pid}", "POST",
                {"status": "publish", "date": now.strftime("%Y-%m-%dT%H:%M:%S")})
    print(pid, "PUT→", st, (p.get("status"), p.get("date"), p.get("link")) if isinstance(p, dict) else p)

time.sleep(3)
for pid in IDS:
    st, c = api(f"/wp-json/wp/v2/posts/{pid}?context=edit&_fields=id,slug,status,date,link")
    print(f"#{pid}: status={c.get('status')} date={c.get('date')} slug={c.get('slug')} link={c.get('link')}")

print("\n=== cek HTTP dari luar ===")
for slug in ("digital-marketing-bisnis-properti", "digital-marketing-bisnis-manufaktur"):
    url = f"https://studiosoft.id/{slug}/"
    code = subprocess.run(["curl", "-s", "-4", "-o", "/dev/null", "-w", "%{http_code}",
                           "--http1.1", "--max-time", "90", url],
                          capture_output=True, text=True).stdout
    print(code, url)
