#!/usr/bin/env python3
"""Atur ulang jadwal & simpan artikel duplikat di StudioSoft.

- duplikat (fokus/isi bertabrakan) → dipindah ke DRAF (tidak tayang)
- artikel yang sudah tayang → dijadwalkan ulang ke slot 08:00 WIB pada tanggal tertentu

Pakai: python3 ss_jadwal_atur.py [--go]
"""
import base64, json, os, sys, time, urllib.error, urllib.request
from datetime import datetime, timedelta, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
S = "https://studiosoft.id"
AUTH = base64.b64encode(b"bambangbot:q26r RePo BVy6 pwU2 F3z7 ouyl").decode()
UA = {"User-Agent": "Mozilla/5.0"}
BACKUP = f"{WS}/ss_jadwal_backup"
os.makedirs(BACKUP, exist_ok=True)
WIB = timezone(timedelta(hours=7))
JAM = "08:00:00"

# id → alasan (dipindah ke draf)
SIMPAN_DRAF = {
    9227: "duplikat #9290 (agency vs freelancer) + fokus 'digital agency surabaya' bentrok beranda & #2771",
    9229: "duplikat #9120, kata kunci fokus sama: jasa maintenance wordpress",
}
# id → tanggal tayang (08:00 WIB)
JADWAL = {
    9260: "2026-10-15",
    9288: "2026-10-16",
    9290: "2026-10-17",
    9292: "2026-10-18",
}


def rest(path, method="GET", data=None):
    h = {"Authorization": f"Basic {AUTH}", **UA}
    body = None
    if data is not None:
        body = json.dumps(data).encode()
        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()[:250]
        except Exception:
            time.sleep(4)
    return 0, "gagal"


def info(pid):
    st, d = rest(f"/wp-json/wp/v2/posts/{pid}?context=edit"
                 f"&_fields=id,slug,link,status,date,title,content,meta")
    return d if isinstance(d, dict) else {}


print("=== rencana ===")
for pid, alasan in SIMPAN_DRAF.items():
    i = info(pid)
    print(f"  ➜ DRAF   #{pid} «{i.get('title', {}).get('raw', '')[:52]}» — {alasan}")
for pid, tgl in JADWAL.items():
    i = info(pid)
    print(f"  ➜ JADWAL #{pid} «{i.get('title', {}).get('raw', '')[:52]}» → {tgl} {JAM[:5]} WIB"
          f" (sekarang: {i.get('status')} {str(i.get('date'))[:16]})")

if "--go" not in sys.argv:
    print("\n(dry run — pakai --go)")
    sys.exit(0)

log = []
for pid, alasan in SIMPAN_DRAF.items():
    i = info(pid)
    open(f"{BACKUP}/post_{pid}_sebelum.txt", "w").write(i.get("content", {}).get("raw", ""))
    json.dump({"id": pid, "status": i.get("status"), "date": i.get("date"),
               "title": i.get("title", {}).get("raw"), "meta": i.get("meta")},
              open(f"{BACKUP}/post_{pid}_sebelum.json", "w"), ensure_ascii=False, indent=1)
    st, d = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"status": "draft"})
    cek = info(pid)
    ok = isinstance(d, dict) and cek.get("status") == "draft"
    print(f"  #{pid} → draf: HTTP {st} · status sekarang {cek.get('status')} {'✅' if ok else '❌'}")
    log.append({"id": pid, "aksi": "draf", "alasan": alasan, "ok": bool(ok)})

for pid, tgl in JADWAL.items():
    i = info(pid)
    open(f"{BACKUP}/post_{pid}_sebelum.txt", "w").write(i.get("content", {}).get("raw", ""))
    st, d = rest(f"/wp-json/wp/v2/posts/{pid}", "POST", {"status": "future", "date": f"{tgl}T{JAM}"})
    time.sleep(1)
    cek = info(pid)
    ok = (cek.get("status") == "future" and str(cek.get("date", "")).startswith(tgl)
          and cek.get("slug") == i.get("slug"))
    print(f"  #{pid} → {tgl} {JAM[:5]}: HTTP {st} · status {cek.get('status')} · date {cek.get('date')} "
          f"· slug {cek.get('slug')} {'✅' if ok else '❌'}")
    log.append({"id": pid, "aksi": "jadwal", "tanggal": tgl, "ok": bool(ok),
                "slug": cek.get("slug"), "date": cek.get("date")})

json.dump(log, open(f"{WS}/drafts/ss_jadwal_atur_log.json", "w"), ensure_ascii=False, indent=1)
print(f"\n  selesai: {sum(1 for x in log if x['ok'])}/{len(log)} langkah cocok → drafts/ss_jadwal_atur_log.json")

print("\n=== jadwal sekarang (urut tanggal) ===")
st, d = rest("/wp-json/wp/v2/posts?status=future&per_page=100&orderby=date&order=asc"
             "&_fields=id,slug,date,title")
tanggal = {}
for p in d:
    tanggal.setdefault(p["date"][:10], []).append(p)
for t in sorted(tanggal):
    for p in tanggal[t]:
        print(f"  {t} {p['date'][11:16]} | #{p['id']:>5} | {p['title']['rendered'][:58]}")
harian = [t for t in sorted(tanggal)]
print(f"\n  total menunggu tayang: {len(d)} artikel, {len(harian)} hari "
      f"({harian[0]} s/d {harian[-1]})")
ganda = {t: len(v) for t, v in tanggal.items() if len(v) > 1}
print(f"  hari dengan lebih dari satu artikel: {ganda if ganda else 'tidak ada'}")
