#!/usr/bin/env python3
"""Mirror jadwal IG LEIT (27-77) ke TikTok LEIT — 1/hari, 10:00 WIB, mulai 18 Agustus 2026.
Caption & gambar sama dengan postingan IG LEIT. Log: mirror_tiktok_run.log
"""
import json, os, re, sys, time
from datetime import date, timedelta
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import get_client, ACC

ROOT = os.path.dirname(os.path.abspath(__file__))
CAP_DIR = os.path.join(ROOT, "captions")
LOG = os.path.join(ROOT, "mirror_tiktok_run.log")
DRY = "--dry" in sys.argv

client = get_client()

# ── 1. Kumpulkan urutan gambar (sama dengan pasang_repliz.py: 27-77, skip 31) ──
urutan = []
for n in range(27, 78):
    if n == 31:
        continue
    folder = "27-40" if n <= 40 else "41-50" if n <= 50 else "51-60" if n <= 60 else "61-77"
    path = os.path.join(ROOT, folder, f"{n}.png")
    if os.path.exists(path):
        urutan.append((n, path))
print(f"Total gambar: {len(urutan)}")

# ── 2. Parse caption (sama dengan pasang_repliz.py) ──
def parse_caption(num):
    cf = os.path.join(CAP_DIR, f"{num}.json")
    if not os.path.exists(cf):
        return None
    data = json.load(open(cf))
    text = data.get("analysis", "")
    if text.startswith("ERROR"):
        return None
    cap_match = re.search(r"\[CAPTION\](.*?)(?=\[HASHTAG\]|\[DESKRIPSI\]|\Z)", text, re.S)
    tag_match = re.search(r"\[HASHTAG\](.*?)(?=\[CAPTION\]|\Z)", text, re.S)
    caption = cap_match.group(1).strip() if cap_match else ""
    hashtags = tag_match.group(1).strip() if tag_match else "#LEIT #LEITSurabaya #KursusBahasaInggris"
    final = caption
    if hashtags and hashtags not in final:
        final = f"{final}\n\n{hashtags}"
    return final

missing = [n for n, p in urutan if not os.path.exists(os.path.join(CAP_DIR, f"{n}.json"))]
if missing:
    print(f"⚠️ Analisis belum lengkap! Kurang: {missing}")
    sys.exit(1)

# ── 3. Jadwal: mulai 18 Agu 2026 (slot 17 Agu sudah lewat), 1/hari, 10:00 WIB = 03:00 UTC ──
start = date(2026, 8, 18)
print(f"\n{'='*70}")
print(f"{'Gambar':<8}{'Tanggal':<14}{'Jam':<8}{'Caption':<10}Status")
print(f"{'='*70}")

log_lines = []
ok, fail = 0, 0
for i, (n, path) in enumerate(urutan):
    tgl = start + timedelta(days=i)
    schedule_at = f"{tgl.isoformat()}T03:00:00.000Z"  # 10:00 WIB

    caption = parse_caption(n)
    if caption is None:
        line = f"{n}.png      {tgl}  10:00 WIB  {'':<10}❌ NO_CAPTION"
        print(line)
        log_lines.append(line)
        fail += 1
        continue

    caption_disp = caption.replace("\n", " ")[:40]
    if DRY:
        line = f"{n}.png      {tgl}  10:00 WIB  {caption_disp:<10}🟡 DRY"
        print(line)
        log_lines.append(line)
        ok += 1
        continue

    try:
        result = client.schedule_image(
            ACC.LEIT_TIKTOK, caption, schedule_at,
            path, filename=f"leit_ig_{n}_tiktok.jpg",
            title=f"LEIT {n}", topic="LEIT TikTok Harian"
        )
        sid = result.get("scheduleId") or result.get("_id") or result.get("id") or result
        line = f"{n}.png      {tgl}  10:00 WIB  {caption_disp:<10}✅ {str(sid)[:30]}"
        print(line)
        log_lines.append(line)
        ok += 1
    except Exception as e:
        line = f"{n}.png      {tgl}  10:00 WIB  {caption_disp:<10}❌ {str(e)[:80]}"
        print(line)
        log_lines.append(line)
        fail += 1
    time.sleep(1.5)

print(f"\n{'='*70}")
print(f"Selesai: {ok} OK, {fail} gagal")

with open(LOG, "w", encoding="utf-8") as f:
    f.write("\n".join(log_lines) + f"\n\nSelesai: {ok} OK, {fail} gagal\n")
print(f"Log: {LOG}")
