#!/usr/bin/env python3
"""
LEIT Threads Scheduler — cron job harian.
Jalan tiap jam untuk cek slot kosong.
Post nested 3 thread di slot kosong berikutnya.
Slot: 05:00, 08:00, 11:00, 14:00, 17:00, 20:00, 23:00 WIB
Konten bergilir dari 10 niche, setiap konten UNIK — tidak ada yang redundant.
Menggunakan bahasa yang sopan dan baik.
"""
import json, urllib.request, sys, os, random, hashlib
from datetime import datetime, timezone, timedelta

from repliz_client import HEADERS, BASE, ACC
from diskusi_engine import tambahkan_diskusi  # pancingan diskusi (FIXED 7 Agt 2026)
ACCOUNT_ID = ACC.LEIT_THREADS  # LEIT Threads

LOG_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/leit_threads_log.txt"
STATE_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/leit_threads_state.json"
HISTORY_FILE = "/home/mantapman/.hermes/profiles/atun/workspace/leit_threads_history.json"

WIB = timezone(timedelta(hours=7))

SLOTS = [
    (5, 0), (8, 0), (11, 0), (14, 0), (17, 0), (20, 0), (23, 0)
]

NICHES = [
    "English Communication Mastery",
    "Leadership & Character Development",
    "Public Speaking & Communication Skills",
    "Education & Parenting",
    "Student Transformation",
    "Career & Professional English",
    "Study Abroad Preparation",
    "Future Skills",
    "LEIT Method & Experience",
    "LEIT Surabaya Lifestyle",
    "TOEFL & IELTS Preparation",
    "Info Program & Promo LEIT",
    "Belajar dari Artikel LEIT",
    "Bahasa Inggris untuk Karir",
    "Program Anak di LEIT",
    "Kenapa Memilih LEIT",
    "Bahasa Inggris untuk Mahasiswa",
    "Testimoni & Kisah Sukses",
    "Informasi Umum & FAQ",
    "Semangat Belajar & Motivasi",
    "Persiapan Studi Luar Negeri",
    "Belajar Bahasa Inggris Efektif",
    "Tips & Trik LEIT",
    "Pengembangan Diri",
    "Komunitas & Keluarga LEIT",
    "Inovasi Pembelajaran",
    "Karier & Masa Depan",
    "Belajar Fleksibel",
    "Metode Speaking Based",
    "Program Unggulan LEIT",
]

# ============================================================
# BANK KONTEN LEIT — Batch 2 (semua fresh, unik, bahasa sopan)
# ============================================================
with open('/home/mantapman/.hermes/profiles/atun/workspace/leit_threads_content.json', 'r') as f:
    CONTENT_SERIES = json.load(f)


def content_hash(text):
    """Buat hash dari konten untuk cek duplikasi."""
    return hashlib.md5(text.encode()).hexdigest()


def log(msg):
    ts = datetime.now(WIB).strftime("%Y-%m-%d %H:%M:%S")
    line = f"[{ts} WIB] {msg}"
    print(line)
    with open(LOG_FILE, "a") as f:
        f.write(line + "\n")


def load_state():
    try:
        with open(STATE_FILE) as f:
            return json.load(f)
    except:
        return {"last_series": -1, "posted_today": []}


def save_state(state):
    with open(STATE_FILE, "w") as f:
        json.dump(state, f)


def load_history():
    try:
        with open(HISTORY_FILE) as f:
            return json.load(f)
    except:
        return {"posts": [], "content_hashes": []}


def save_history(hist):
    with open(HISTORY_FILE, "w") as f:
        json.dump(hist, f, indent=2)


def get_next_slot(now_hour, now_min):
    """Cari slot kosong berikutnya berdasarkan waktu sekarang."""
    today = datetime.now(WIB).date()
    for h, m in SLOTS:
        if h > now_hour or (h == now_hour and m > now_min):
            one_day = timedelta(days=1)
            return datetime(today.year, today.month, today.day, h, m, tzinfo=WIB)
    return None


def post_to_repliz(account_id, content, schedule_time):
    """Posting ke Repliz di waktu tertentu, return scheduleId jika sukses."""
    url = f"{BASE}/public/schedule"
    title_lines = content.strip().split("\n")
    title = title_lines[0][:60] if title_lines else "LEIT Surabaya"
    
    payload = {
        "accountId": account_id,
        "title": title,
        "description": content,
        "platform": "threads",
        "type": "text",
        "medias": [],
        "topic": "LEIT",
        "scheduleAt": schedule_time.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
        "timezone": "Asia/Jakarta"
    }
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, headers=HEADERS, method="POST")
    try:
        with urllib.request.urlopen(req) as resp:
            result = json.loads(resp.read().decode())
            post_id = result.get("scheduleId") or result.get("id") or result.get("data", {}).get("id")
            log(f"✅ Posted at {schedule_time.strftime('%H:%M')} → ID: {post_id}")
            return post_id
    except urllib.error.HTTPError as e:
        err_body = e.read().decode()
        log(f"❌ Repliz error: {e.code} {err_body}")
        return None
    except Exception as e:
        log(f"❌ Error: {e}")
        return None


def main():
    now = datetime.now(WIB)
    today_str = now.strftime("%Y-%m-%d")
    now_hour, now_min = now.hour, now.minute
    now_total = now_hour * 60 + now_min
    
    log(f"🔄 LEIT Threads Check — {today_str} {now_hour:02d}:{now_min:02d} WIB")
    
    state = load_state()
    hist = load_history()
    used_hashes = set(hist.get("content_hashes", []))
    
    # Reset kalo hari baru
    if state.get("date") != today_str:
        state = {"date": today_str, "last_series": state.get("last_series", -1), "posted_today": []}
        save_state(state)
    
    # Cari slot berikutnya yang belum terisi
    next_slot = None
    for h, m in SLOTS:
        slot_total = h * 60 + m
        if slot_total > now_total and slot_total not in state.get("posted_today", []):
            next_slot = (h, m)
            break
    
    if next_slot is None:
        log("⏭️ Semua slot sudah terisi atau tidak ada slot tersisa hari ini.")
        return
    
    # Pilih seri konten berikutnya (bergilir)
    last_series = state.get("last_series", -1)
    next_series = (last_series + 1) % len(CONTENT_SERIES)
    series = CONTENT_SERIES[next_series]["posts"]
    
    # Cek apakah konten di seri ini ada yang duplikat (hash)
    series_hashes = [content_hash(c) for c in series]
    if any(h in used_hashes for h in series_hashes):
        log(f"⚠️ Series {next_series+1} mengandung konten yang sudah pernah diposting. Cari seri lain...")
        # Coba seri berikutnya yang aman
        for offset in range(1, len(CONTENT_SERIES)):
            candidate = (next_series + offset) % len(CONTENT_SERIES)
            candidate_hashes = [content_hash(c) for c in CONTENT_SERIES[candidate]["posts"]]
            if not any(h in used_hashes for h in candidate_hashes):
                next_series = candidate
                series = CONTENT_SERIES[next_series]["posts"]
                series_hashes = candidate_hashes
                log(f"✅ Beralih ke Series {next_series+1}")
                break
        else:
            log("❌ Semua seri konten sudah habis dipakai. Butuh konten baru!")
            return
    
    schedule_time = datetime(now.year, now.month, now.day, next_slot[0], next_slot[1], tzinfo=WIB)
    
    # Post 3 nested thread
    post_ids = []
    for i, content in enumerate(series):
        # Pancingan diskusi di post utama (FIXED 7 Agt 2026)
        if i == 0:
            content = tambahkan_diskusi(content, "threads", "pendidikan")
        if i == 0:
            pid = post_to_repliz(ACCOUNT_ID, content, schedule_time)
        else:
            reply_time = schedule_time + timedelta(minutes=2 * i)
            pid = post_to_repliz(ACCOUNT_ID, content, reply_time)
        
        if pid:
            post_ids.append(pid)
    
    if post_ids:
        state["last_series"] = next_series
        posted = state.get("posted_today", [])
        posted.append(next_slot[0] * 60 + next_slot[1])
        state["posted_today"] = posted
        save_state(state)
        
        # Simpan history + hash
        if "posts" not in hist:
            hist["posts"] = []
        if "content_hashes" not in hist:
            hist["content_hashes"] = []
        
        hist["posts"].append({
            "date": today_str,
            "time": f"{next_slot[0]:02d}:{next_slot[1]:02d}",
            "series": next_series,
            "niche": NICHES[next_series % len(NICHES)],
            "post_ids": post_ids
        })
        hist["content_hashes"].extend(series_hashes)
        save_history(hist)
        
        log(f"📦 Series {next_series+1} ({NICHES[next_series % len(NICHES)]}) — {len(post_ids)}/3 posted di slot {next_slot[0]:02d}:{next_slot[1]:02d} WIB")
    else:
        log("⚠️ Gagal posting. Coba lagi di pengecekan berikutnya.")


if __name__ == "__main__":
    main()

