#!/usr/bin/env python3
"""Schedule cross-account Threads: 5 akun saling mention & reply
StudioSoft → @ukyhandoko → Tslaw → TSC → DAS
"""
import sys, json
from datetime import datetime, timezone, timedelta
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client, ACC
from diskusi_engine import tambahkan_diskusi, AKUN_INDUSTRI  # pancingan diskusi

client = get_client()
JSON_FILE = sys.argv[1] if len(sys.argv) > 1 else None

def slot(h, year=2026, month=7, day=29):
    dt = datetime(year, month, day, h) - timedelta(hours=7)
    return dt.strftime("%Y-%m-%dT%H:%M:%S.000Z")

def schedule_one(acc, text, schedule_at, title, reply_to=None):
    if reply_to:
        r = client.create_schedule(acc, text, schedule_at, title=title, replies=[reply_to])
    else:
        r = client.schedule_text(acc, text, schedule_at, title=title)
    sid = r.get("scheduleId", "?")
    print(f"   ✅ {sid}")
    return sid

# ── Baca dari file JSON kalo ada ──
if JSON_FILE:
    with open(JSON_FILE) as f:
        data = json.load(f)
    accounts_data = data.get("accounts", [])
    date_str = data.get("date", "")
    parts = date_str.split("-")
    Y, M, D = int(parts[0]), int(parts[1]), int(parts[2])

    print(f"📅 SCHEDULE CROSS-ACCOUNT — {date_str}")
    print("=" * 55)

    last_sid = None
    for item in accounts_data:
        acc_key = item["account"].lower()
        acc_map = {
            "studiosoft": ACC.STUDIOSOFT_THREADS,
            "uky": ACC.UKY_THREADS,
            "tslaw": ACC.TSLAW_THREADS,
            "tsc": ACC.TSC_THREADS,
            "das": ACC.DAS_THREADS,
        }
        if acc_key not in acc_map:
            print(f"   ⚠️  Unknown account: {acc_key}")
            continue

        text = item["text"]
        slot_h = item["slot"]
        sched_at = slot(slot_h, Y, M, D)
        title = f"{acc_key.capitalize()} - Daily"

        # Pancingan diskusi (FIXED 7 Agt 2026) — post utama (bukan reply)
        if item.get("replyTo") is None:
            industri = AKUN_INDUSTRI.get(acc_key + "_threads", "umum")
            text = tambahkan_diskusi(text, "threads", industri)

        print(f"{slot_h}:00 {acc_key}...", end=" ")
        if item.get("replyTo") is not None and last_sid:
            last_sid = schedule_one(acc_map[acc_key], text, sched_at, title, reply_to=last_sid)
        else:
            last_sid = schedule_one(acc_map[acc_key], text, sched_at, title)

    print("\n✅ ALL DONE!")
    sys.exit(0)

# ── Fallback: langsung schedule dari sini ──
print("⚠️  No JSON file. Use: python3 schedule_diskusi_cross_account.py content.json")
print("   Format lihat cron prompt.")
