#!/usr/bin/env python3
"""
Twitter @UkyHandoko — Growth Theory Ep.01 "Evolusi SEO"
Konsep ala TORCH "Bag Theory" → storytelling series edukasi.
3 tweet nested (post → reply1 → reply2), max 280 char, gaya humanis "saya".
Dijadwalkan ke slot kosong berikutnya (besok 05:00 WIB bila slot hari ini penuh).
"""
import json, sys, os, hashlib, urllib.request, urllib.error
from datetime import datetime, timezone, timedelta

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE, ACC
from twitter_uky_scheduler import (validate_text, log, load_json, save_json,
                                   SLOT_HOURS, ACCOUNT_ID, THEME_TRACK_FILE)

WIB = timezone(timedelta(hours=7))

# ── Konten Growth Theory Ep.01 (unik, gaya ngomong, awareness) ──
THEME_NAME = "growth theory ep1 evolusi seo"
POST = ("Dulu, bisnis cukup punya website buat keliatan di internet. Tahun 1998-2010, "
        "yang rajin nempel kata kunci & pasang link asal, langsung nangkring di Google. "
        "Zaman itu, yang penting ADA. Sekarang? Jauh beda.")
REPLY1 = ("Sekarang Google makin pinter baca niat. Konten asal nggak cukup — yang penting "
          "DIPERCAYA: konten bermanfaat, reputasi baik, pengalaman nyaman. Yang nggak cuma "
          "muncul, tapi beneran menjawab, itu yang menang.")
REPLY2 = ("Dan ke depannya? Orang makin sering nanya ke AI: ChatGPT, Gemini, Perplexity. "
          "Bisnis yang dipahami & direkomendasikan AI yang bakal menang. Ini evolusi baru "
          "cara orang menemukan bisnis — dan baru mulai. Saya bakal bahas pelan-pelan.")

# ── Cek slot kosong (hari ini penuh → besok jam 05:00 WIB) ──
def next_free_slot():
    from twitter_uky_scheduler import get_schedules_today, get_pending_slot
    scheds = get_schedules_today()
    idx = get_pending_slot(scheds)
    if idx is not None:
        return idx, datetime.now(WIB).strftime("%Y-%m-%d")
    # Semua slot hari ini terisi → besok 05:00 WIB (slot pertama)
    tomorrow = (datetime.now(WIB) + timedelta(days=1)).strftime("%Y-%m-%d")
    return 0, tomorrow


def post_nested_date(texts, slot_hour, date_str):
    """Nested 3 tweet pada tanggal & jam tertentu."""
    parent_id = None
    ids = []
    for i, text in enumerate(texts):
        wib_dt = datetime.strptime(f"{date_str}T{slot_hour:02d}:{i:02d}:00", "%Y-%m-%dT%H:%M:%S")
        iso_utc = (wib_dt - timedelta(hours=7)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        payload = {
            "accountId": ACCOUNT_ID,
            "title": "",
            "description": text,
            "topic": "SEO" if i == 0 else "",
            "type": "text",
            "medias": [],
            "scheduleAt": iso_utc,
            "replies": [parent_id] if parent_id else [],
        }
        body = json.dumps(payload).encode()
        req = urllib.request.Request(f"{BASE}/public/schedule", data=body, headers=HEADERS, method="POST")
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                result = json.loads(r.read())
                sid = result.get("scheduleId", result.get("id", "?"))
                ids.append(sid)
                parent_id = sid
                log(f"✅ [Growth Theory] Tweet {i+1} → {sid} | {date_str} {slot_hour:02d}:{i:02d} WIB")
        except urllib.error.HTTPError as e:
            err = e.read().decode()
            log(f"❌ [Growth Theory] Tweet {i+1}: HTTP {e.code} — {err[:200]}")
            raise
    return ids


def main():
    print("🐦 TWITTER @UkyHandoko — GROWTH THEORY Ep.01 (Evolusi SEO)")
    # 1. Validasi teks (max 280 + link cek)
    texts = [POST, REPLY1, REPLY2]
    validated = []
    for i, t in enumerate(texts):
        try:
            validated.append(validate_text(t, label=f"Tweet {i+1}"))
        except ValueError as e:
            log(f"SKIP [Growth Theory]: {e}")
            return
    for i, t in enumerate(validated):
        print(f"   Tweet {i+1}: {len(t)} char")
        print(f"     {t[:100]}...")

    # 2. Anti duplikasi
    used = load_json(THEME_TRACK_FILE, {})
    h = hashlib.md5(THEME_NAME.encode()).hexdigest()
    if h in used:
        log("SKIP [Growth Theory]: tema sudah pernah dipakai.")
        return
    # Fallback: cek kemiripan konten via hash isi post
    for v in used.values():
        if isinstance(v, dict) and v.get("theme") == THEME_NAME:
            log("SKIP [Growth Theory]: tema sudah pernah dipakai.")
            return

    # 3. Tentukan slot
    slot_idx, date_str = next_free_slot()
    slot_wib = SLOT_HOURS[slot_idx]
    print(f"   🎯 Slot: {date_str} {slot_wib:02d}:00 WIB")

    # 4. Kirim
    try:
        ids = post_nested_date(validated, slot_wib, date_str)
    except Exception as e:
        log(f"❌ [Growth Theory] Gagal posting: {str(e)[:150]}")
        return

    # 5. Tracker
    used[h] = {"theme": THEME_NAME, "posted": datetime.now(WIB).strftime("%Y-%m-%d %H:%M")}
    save_json(THEME_TRACK_FILE, used)
    print("✅ Selesai — Growth Theory Ep.01 terjadwal di", date_str, f"{slot_wib:02d}:00 WIB")


if __name__ == "__main__":
    main()
