#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Jadwalkan 18 caption FB TS Law (artikel tslaw.id) — 12 Agustus 2026
- 2 posting/hari: 09:00 & 19:00 WIB (hindari jam existing: 05/06/10/11/15/16/20/01)
- Mulai 13 Agustus 2026 → 9 hari
- Cek link 200 OK sebelum kirim
- Update tslaw_fb_history.json setelah sukses
"""
import sys, json, os, urllib.request, urllib.error, re
from datetime import datetime, timedelta, timezone

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE, ACC
from _tslaw_18_captions import CAPTIONS

ACCOUNT_ID = ACC.TSLAW_FB
HISTORY_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_fb_history.json"
LOG_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/tslaw_log.txt"
WIB = timezone(timedelta(hours=7))

# Slot: 13-21 Agustus 2026, jam 09:00 & 19:00 WIB
START = datetime(2026, 8, 13, tzinfo=WIB)
SLOTS = []
for day in range(9):
    d = START + timedelta(days=day)
    SLOTS.append(d.replace(hour=9, minute=0))
    SLOTS.append(d.replace(hour=19, minute=0))


def check_link(url):
    try:
        req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}, method="GET")
        with urllib.request.urlopen(req, timeout=20) as r:
            return r.status == 200
    except Exception:
        return False


def log(msg):
    with open(LOG_FILE, "a") as f:
        f.write(f"[{datetime.now(WIB).strftime('%Y-%m-%d %H:%M:%S')} WIB] {msg}\n")
    print(msg)


def main():
    print("=" * 60)
    print("📌 JADWALKAN 18 POSTINGAN ARTIKEL FB TS LAW")
    print(f"   {datetime.now(WIB).strftime('%Y-%m-%d %H:%M')} WIB")
    print("=" * 60)

    if len(CAPTIONS) != 18:
        log(f"❌ Jumlah caption {len(CAPTIONS)}, harus 18. Batal.")
        return

    # 1. Cek semua link 200
    print("🔍 Cek link artikel...")
    for c in CAPTIONS:
        ok = check_link(c["url"])
        print(f"   {'✅' if ok else '❌'} {c['url']}")
        if not ok:
            log(f"❌ Link mati: {c['url']} — batal semua.")
            return

    # 2. Kirim schedule
    posted = []
    for i, (cap, slot_wib) in enumerate(zip(CAPTIONS, SLOTS), 1):
        iso_utc = (slot_wib - timedelta(hours=7)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        payload = {
            "accountId": ACCOUNT_ID,
            "title": "",
            "description": cap["caption"],
            "topic": "",
            "type": "text",
            "medias": [],
            "scheduleAt": iso_utc,
            "replies": [],
        }
        body = json.dumps(payload).encode()
        req = urllib.request.Request(f"{BASE}/public/schedule", data=body, headers={**HEADERS, "Content-Type": "application/json"}, method="POST")
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                result = json.loads(r.read())
                sid = result.get("scheduleId", result.get("id", "?"))
                log(f"✅ [{i}/18] {slot_wib.strftime('%d/%m %H:%M')} WIB → {sid} | {cap['title'][:50]}")
                posted.append({"date": slot_wib.strftime("%Y-%m-%d"), "time": slot_wib.strftime("%H:%M"),
                               "platform": "facebook", "article_url": cap["url"], "schedule_id": sid, "title": cap["title"]})
        except urllib.error.HTTPError as e:
            err = e.read().decode()[:300]
            log(f"❌ [{i}/18] Gagal: HTTP {e.code} — {err}")
            log("   ⚠️ HENTIKAN — jangan lanjut agar tidak sebagian terkirim.")
            break

    # 3. Update history
    if posted:
        hist = {"posts": [], "article_urls": []}
        if os.path.exists(HISTORY_FILE):
            with open(HISTORY_FILE) as f:
                hist = json.load(f)
        hist.setdefault("posts", []).extend(posted)
        hist.setdefault("article_urls", []).extend([p["article_url"] for p in posted])
        with open(HISTORY_FILE, "w") as f:
            json.dump(hist, f, indent=2)
        log(f"💾 History diperbarui: {len(posted)} postingan baru ({HISTORY_FILE})")

    print("=" * 60)
    print(f"✅ Selesai — {len(posted)}/18 terjadwal")
    print("=" * 60)


if __name__ == "__main__":
    main()
