#!/usr/bin/env python3
"""Pasang semua gambar LEIT (27-77) ke Repliz — jadwal harian 10:00 WIB mulai 16 Agustus 2026.
Caption: dari hasil analisis (2 paragraf + CTA + hashtag)."""
import json, os, re, sys, time
from datetime import date, timedelta
from repliz_client import get_client, ACC

ROOT = "leit_ig_40"
CAP_DIR = os.path.join(ROOT, "captions")
DRY = "--dry" in sys.argv

client = get_client()

# ── 1. Kumpulkan urutan gambar ──
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. Baca hasil analisis ──
def parse_caption(num):
    """Parse hasil analisis jadi caption final (2 paragraf + hashtag)."""
    cf = os.path.join(CAP_DIR, f"{num}.json")
    if not os.path.exists(cf):
        return None, "NO_ANALYSIS"
    data = json.load(open(cf))
    text = data.get("analysis", "")
    if text.startswith("ERROR"):
        return None, text

    # Ambil blok CAPTION & HASHTAG
    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"

    # Bersihkan caption: minimal 2 paragraf
    paras = [p.strip() for p in caption.split("\n") if p.strip()]
    if len(paras) < 2:
        caption = caption  # biarkan apa adanya, nanti dicek

    # Pastikan CTA ada di akhir paragraf 2
    final = caption
    if hashtags and hashtags not in final:
        final = f"{final}\n\n{hashtags}"
    return final, text[:80]

# ── 3. Cek kelengkapan analisis ──
missing = []
for n, path in urutan:
    cf = os.path.join(CAP_DIR, f"{n}.json")
    if not os.path.exists(cf):
        missing.append(n)
if missing:
    print(f"⚠️ Analisis belum lengkap! Kurang: {missing}")
    print("Tunggu analisis selesai dulu, atau jalankan ulang nanti.")
    sys.exit(1)

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

ok, fail = 0, 0
for i, (n, path) in enumerate(urutan):
    tgl = start + timedelta(days=i)
    schedule_at = f"{tgl.isoformat()}T10:00:00.000Z"  # WIB sudah dikonversi? No — ini UTC!
    # Konversi: 10:00 WIB = 03:00 UTC
    schedule_at = f"{tgl.isoformat()}T03:00:00.000Z"

    caption, status = parse_caption(n)
    if caption is None:
        print(f"{n}.png      {tgl}  10:00 WIB  {'':<10}❌ {status[:60]}")
        fail += 1
        continue

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

    try:
        # Upload ke WP dulu biar dapat URL, lalu schedule image ke Repliz
        result = client.schedule_image(
            ACC.LEIT_IG, caption, schedule_at,
            path, filename=f"leit_ig_{n}.png",
            title=f"LEIT {n}", topic="LEIT Instagram Harian"
        )
        sid = result.get("_id") or result.get("id") or result
        print(f"{n}.png      {tgl}  10:00 WIB  {caption_disp:<10}✅ {str(sid)[:30]}")
        ok += 1
    except Exception as e:
        print(f"{n}.png      {tgl}  10:00 WIB  {caption_disp:<10}❌ {str(e)[:80]}")
        fail += 1
    time.sleep(1.5)  # jeda biar gak kena rate limit

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