#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TS Law — Perpanjang stok berita GELOMBANG 2 (7-11 Sep 2026).
Jadwal existing gelombang 1 = 2-6 Sep. Script utama tslaw_berita_scheduler.py
selalu mulai dari besok (3 Sep) sehingga akan BENTROK — maka extend manual ini
menjadwalkan mulai 7 Sep, reuse fungsi caption dari scheduler utama,
lalu update state (used + posts) supaya anti-duplikat tetap jalan.
"""
import sys, os, json
from datetime import datetime, timedelta, timezone
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
import tslaw_berita_scheduler as TBS
from repliz_client import ReplizClient

WIB = timezone(timedelta(hours=7))
ROOT = "/home/mantapman/.hermes/profiles/atun/workspace"
STATE = os.path.join(ROOT, "tslaw_berita_history.json")

st = TBS.load_state()
used = set(st["used"])
client = ReplizClient()

# 5 berita gelombang 2 = 5 entri terakhir di BERITA (index 5..9)
gelombang2 = TBS.BERITA[5:10]
print(f"Berita gelombang 2: {len(gelombombang2) if False else len(gelombang2)}")

# Mulai 7 Sep 2026 (hari setelah jadwal existing 2-6 Sep)
start = datetime(2026, 9, 7, tzinfo=WIB)
ok = fail = 0
for i, (judul, url, niche, angle) in enumerate(gelombang2):
    key = TBS.hsh(judul)
    if key in used:
        print(f"  ⏭️  sudah dipakai: {judul[:50]}")
        continue
    tgl = start + timedelta(days=i)
    ds = tgl.strftime("%Y-%m-%d")

    # LinkedIn (replies=[] WAJIB — FIX 2 Sep 2026: LinkedIn Repliz tidak support
    # replies, error "Cannot read properties of undefined (reading 'postId')".
    # Dipatch 6 Sep 2026: versi awal script ini masih menaruh 2 replies di sini;
    # jadwal 7-11 Sep yang terlanjur terpasang sudah di-PUT replies=[] (sweep 5 Sep).
    # Pola sukses terbukti 25 Agu-6 Sep = replies: [].)
    at_li = tgl.replace(hour=10, minute=0, tzinfo=WIB).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    try:
        res = client.create_schedule(
            TBS.TSLAW_LI, TBS.caption_li(judul, url, niche, angle), at_li,
            title=f"TS Law — {niche}: {judul[:40]}", topic=niche, type_="text",
            replies=[],
        )
        ok += 1
        print(f"  ✅ {ds} 10:00 WIB | LinkedIn | {judul[:55]}")
    except Exception as e:
        fail += 1
        print(f"  ❌ {ds} LinkedIn | {judul[:40]}: {e}")

    # Threads (main + 1 reply) jam 15:00 WIB
    at_t = tgl.replace(hour=15, minute=0, tzinfo=WIB).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")
    try:
        res = client.create_schedule(
            TBS.TSLAW_T, TBS.caption_threads(judul, url, niche, angle), at_t,
            title=f"TS Law — {judul[:40]}", topic=niche, type_="text",
            replies=[{"text": TBS.reply_threads(judul, niche), "username": ""}],
        )
        ok += 1
        print(f"  ✅ {ds} 15:00 WIB | Threads  | {judul[:55]}")
    except Exception as e:
        fail += 1
        print(f"  ❌ {ds} Threads | {judul[:40]}: {e}")

    st["used"].append(key)
    st["posts"].append({"date": ds, "judul": judul, "niche": niche, "url": url})
    TBS.save_state(st)

TBS.save_state(st)
print(f"\n📊 Total: {ok} OK, {fail} gagal")
