#!/usr/bin/env python3
"""Buat 2 post Threads yang di-SKIP guard ownlink longgar (13 Okt 2026):
  - uky   14:00 WIB  (topik Agensi & Layanan)   — guard kena krn post 10:06 memuat "@studiosoft.id" (mention, bukan link artikel)
  - tslaw 17:00 WIB  (topik Law Firm vs Advokat) — guard kena krn post 09:00 memuat "https://tslaw.id" (root, bukan artikel)

Syarat: slot 14:00/17:00 masih kosong (dicek ulang), caption dari threads_content_today.json, standalone (replies=[]).
Lalu: verifikasi dari API + catat ke log_threads_harian.json.
"""
import json
import sys
import time
from datetime import datetime, timedelta, timezone

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, WS)
from repliz_client import get_client, ACC

WIB = timezone(timedelta(hours=7))
LOG = f"{WS}/log_threads_harian.json"
DATE = "2026-10-13"

client = get_client()
content = json.load(open(f"{WS}/threads_content_today.json"))
by_acc = {a["account"]: a for a in content["accounts"]}


def fetch_all():
    docs = []
    for p in range(1, 150):
        got = None
        for i in range(15):
            try:
                got = client.get_schedules(page=p, limit=100)
                break
            except Exception as e:
                print(f"    retry page {p} ({str(e)[:50]})")
                time.sleep(min(40, 3 + 4 * i))
        if got is None:
            raise RuntimeError(f"gagal halaman {p}")
        b = got.get("docs", [])
        if not b:
            break
        docs += b
        if len(b) < 100:
            break
    return docs


def wib_hour(sa):
    try:
        return datetime.fromisoformat(str(sa).replace("Z", "+00:00")).astimezone(WIB)
    except Exception:
        return None


def utc_ts(h):
    return datetime(2026, 10, 13, h, 0, 0, tzinfo=WIB).astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")


print("Mengambil jadwal terbaru...")
docs = fetch_all()
print("total:", len(docs))
print("sekarang (WIB):", datetime.now(WIB).strftime("%Y-%m-%d %H:%M"))

PLAN = [
    ("uky", ACC.UKY_THREADS, 14, "@ukyhandoko"),
    ("tslaw", ACC.TSLAW_THREADS, 17, "Tslaw"),
]

results = []
for key, aid, hour, name in PLAN:
    item = by_acc[key]
    taken = {wib_hour(d.get("scheduleAt")).strftime("%Y-%m-%d %H") for d in docs
             if d.get("accountId") == aid and wib_hour(d.get("scheduleAt"))}
    if f"{DATE} {hour:02d}" in taken:
        print(f"  ⛔ {name}: slot {hour}:00 sudah terisi → SKIP")
        results.append({"account": key, "slot": hour, "status": "slot_taken"})
        continue
    at = utc_ts(hour)
    print(f"\n📝 {name} → {DATE} {hour}:00 WIB (UTC {at})")
    try:
        r = client.create_schedule(aid, item["text"], at, title=item["title"], topic=item["topic"], replies=[])
        sid = r.get("scheduleId") or r.get("_id") or r.get("id") or "?"
        print("  ✅ create:", sid)
        results.append({"account": key, "slot": hour, "status": "ok", "id": sid, "scheduleAt": at,
                        "note": "override guard ownlink longgar (bukan link artikel)"})
    except Exception as e:
        print("  ❌", e)
        results.append({"account": key, "slot": hour, "status": "error", "error": str(e)})

print("\n🔎 Verifikasi dari API...")
docs2 = fetch_all()
by_id = {d.get("_id"): d for d in docs2}
import re
URL_RE = re.compile(r"https?://\S+")
MENT_RE = re.compile(r"@\w+")
for res in results:
    if res["status"] != "ok":
        continue
    d = by_id.get(res["id"])
    if not d:
        print(f"  ⚠️  {res['account']}: id {res['id']} tidak ditemukan di API!")
        continue
    desc = d.get("description") or ""
    print(f"  ✅ {res['account']} {d.get('scheduleAt')} id={d.get('_id')} status={d.get('status')} "
          f"len={len(desc)} link={URL_RE.findall(desc)[:1]} mention={MENT_RE.findall(desc)} "
          f"replies={len(d.get('replies') or [])} topic={d.get('topic')!r} title={d.get('title')!r}")

# ── catat ke log harian ──
log = json.load(open(LOG))
entry = None
for p in log.get("posts", []):
    if p.get("date") == DATE:
        entry = p
if entry is None:
    entry = {"date": DATE, "threads_standalone": []}
    log.setdefault("posts", []).append(entry)
for res in results:
    entry["threads_standalone"].append(res)
    if res["status"] == "ok":
        item = by_acc[res["account"]]
        link = URL_RE.findall(item["text"])[0]
        log.setdefault("threads_used_links", {}).setdefault(DATE, {}).setdefault(res["account"], []).append(
            {"url": link, "slot": res["slot"], "scheduleAt": res["scheduleAt"]})
log["last_date"] = DATE
json.dump(log, open(LOG, "w"), indent=2, ensure_ascii=False)
print("\nlog diperbarui:", DATE, "→", json.dumps(entry, ensure_ascii=False)[:400])
