#!/usr/bin/env python3
"""DAILY IMAGE POSTING — cron 2026-10-26 (job daily-image-posting-all).

Item antrean #92 = uky_quote5_salah_sekali_cukup (seri uky5, kartu ke-5 dari 14).
KARTU: square 1080x1080, varian PUTIH (bg #FFFFFF + teks #122B63) —
rotasi BIRU/PUTIH/ORANGE seri uky5, rata kiri, satu blok tengah vertikal, tanpa separator.

NADA (Bos 5 Okt 2026): santai ("aku"/"kamu"), 0 hashtag, 0 mention internal, tanpa link,
replies=[] -> pancingan diskusi di ekor (OPINI; entri sebelumnya #90 sanjungan, #91 netral).
topic (topic_tag Threads) WAJIB <=45 char.
Jeda: cron terakhir jalan 19 Okt (item #91) -> lane 08:00 sudah terisi s/d 14 Nov.
"""
import json, os, re, sys, subprocess
from datetime import datetime, timezone, timedelta

ROOT = "/home/mantapman/.hermes/profiles/atun/workspace"
sys.path.insert(0, ROOT)
from repliz_client import get_client, IMG_BASE_URL, IMG_DIR, cek_teks_cjk
from PIL import Image
from collections import Counter
import repliz_openssl_transport

repliz_openssl_transport.install(verbose=False)

NL2 = chr(10) * 2
UKY_T = "6a334e89c5ff4ce3a3225a48"          # Threads @ukyhandoko
ITEM_ID = "uky_quote5_salah_sekali_cukup"
FILENAME = "salah_sekali_cukup_putih.png"
SRC = os.path.join(ROOT, "uky5_output", FILENAME)
MEDIA_NAME = "uky_quote5_salah_sekali_cukup.jpg"
TITLE = "Salah Itu Wajar, Mengulanginya Tidak"
TOPIC = "Salah itu wajar, mengulanginya tidak"   # 35 char (<=45)

SLOT_AT = "2026-11-16T01:00:00.000Z"          # 16 Nov 2026 08:00 WIB
SLOT_WIB = "2026-11-16 08:00 WIB"

BODY = (
    "Tim salah itu biasa. Yang bikin aku nggak nyaman kalau salah yang sama kejadian lagi "
    "\u2014 dengan alasan yang sama. \U0001F614"
    + NL2 +
    "Aku nggak butuh orang yang nggak pernah salah. Aku cuma minta satu hal: setelah salah, "
    "ada yang berubah di cara kerjanya. Entah checklist baru, entah kebiasaan ngecek dua kali "
    "sebelum kirim."
)

HOOK = ("Bold statement: tim yang berani ngaku salah dan mau benerin lebih aman daripada tim "
        "yang kelihatan rapi tapi nggak pernah mengakui. Setuju atau nggak?")

CTA_RE = re.compile(r"komentar|pendapat|diskusi|setuju|share|pengalaman|menurut|sepakat|percaya|\?", re.I)
CJK_RE = re.compile(
    "[" + chr(0x4E00) + "-" + chr(0x9FFF) + chr(0x3040) + "-" + chr(0x30FF)
    + chr(0xAC00) + "-" + chr(0xD7AF) + "]"
)
FRASA_RE = re.compile(r"salah itu wajar|mengulanginya|ngaku salah|akui kesalahan|cara kerjanya", re.I)

_UKY = []


def fetch_uky(client, refresh=False):
    if _UKY and not refresh:
        return _UKY[0]
    r = client.get_schedules(page=1, limit=100)
    pages = (r["totalDocs"] + 99) // 100
    docs = list(r["docs"])
    for p in range(2, pages + 1):
        docs.extend(client.get_schedules(page=p, limit=100)["docs"])
    out = [d for d in docs
           if (d.get("accountId") or (d.get("account") or {}).get("id")) == UKY_T]
    if refresh:
        _UKY[:] = [out]
    else:
        _UKY.append(out)
    return out


def wib(d):
    at = d.get("scheduleAt")
    if not at:
        return None
    dt = datetime.fromisoformat(at.replace("Z", "+00:00"))
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt + timedelta(hours=7)


def media_hits(client, media_name, refresh=False):
    hits = []
    for d in fetch_uky(client, refresh=refresh):
        for m in (d.get("medias") or []):
            base = (m.get("url") or "").split("?")[0].rsplit("/", 1)[-1]
            if base == media_name:
                hits.append(d)
                break
    return hits


def build_caption():
    assert BODY.count(NL2) == 1, "BODY harus punya tepat 1 pemisah paragraf"
    cap = BODY + NL2 + HOOK
    log = json.load(open(os.path.join(ROOT, "image_posting_log.json")))
    for e in log:
        if HOOK in (e.get("caption_final") or ""):
            raise RuntimeError("pancingan sudah dipakai di log - tulis yang lain")
        if e.get("item_id") == ITEM_ID:
            raise RuntimeError("item sudah pernah dicatat di log - jangan dobel")
    return cap


def upload():
    os.makedirs(IMG_DIR, exist_ok=True)
    img = Image.open(SRC)
    if img.mode in ("RGBA", "LA", "P"):
        img = img.convert("RGB")
    out = os.path.join(IMG_DIR, MEDIA_NAME)
    img.save(out, format="JPEG", quality=90)
    return f"{IMG_BASE_URL.rstrip('/')}/openclaw-img/{os.path.basename(out)}", out


def check_public(url):
    codes = {}
    for ip in ("103.84.155.153", "103.84.155.217"):
        r = subprocess.run(
            ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "30",
             "--resolve", f"mantapserver.tail3947bb.ts.net:443:{ip}", url],
            capture_output=True, text=True)
        codes[ip] = r.stdout.strip()
    return codes


def main():
    assert os.path.exists(SRC), f"file gambar tidak ada: {SRC}"
    im = Image.open(SRC).convert("RGB")
    assert im.size == (1080, 1080), f"ukuran {im.size} != 1080x1080"
    bg = im.getpixel((5, 540))
    dom = [c for c, _ in Counter(im.get_flattened_data()).most_common(4)]
    print(f"ASET: {SRC} size={im.size} bg_px={bg} warna_dominan={dom[:3]}")
    assert bg == (255, 255, 255), f"bg {bg} bukan PUTIH - rotasi seri uky5 (kartu 5 = putih)"
    assert (18, 43, 99) in dom, f"teks bukan #122B63: {dom[:4]}"

    cap = build_caption()
    print(f"CAPTION ({len(cap)} chars):")
    print(cap)
    assert len(cap) <= 495, f"caption {len(cap)} char > 495"
    assert NL2 in cap and chr(92) + "n" not in cap, "baris baru caption salah"
    assert not re.search(r"@\w+", cap), "ada mention!"
    assert not re.search(r"https?://", cap), "ada link (lane ini tanpa link)"
    assert CTA_RE.search(cap), "tidak ada pancingan diskusi"
    assert "#" not in cap, "ada hashtag (aturan seri: 0 hashtag)"
    assert not CJK_RE.search(cap), "ada teks CJK!"
    assert "gue" not in cap.lower(), "ada kata 'gue'"
    assert len(TOPIC) <= 45, f"topic {len(TOPIC)} char (>45)"
    cek_teks_cjk(cap, TITLE, TOPIC, konteks="image_post uky5 #92")

    c = get_client()

    # 1) tema baru? frasa kunci tidak boleh pernah jadi topik/baris pertama post lain
    semua = fetch_uky(c, refresh=True)
    muncul, jadi_topik = [], []
    for d in semua:
        desc = d.get("description") or ""
        if not FRASA_RE.search(desc):
            continue
        muncul.append(d)
        baris1 = desc.strip().splitlines()[0] if desc.strip() else ""
        if FRASA_RE.search(baris1) or FRASA_RE.search(d.get("topic") or ""):
            jadi_topik.append(d)
    print(f"CEK TEMA frasa 'salah itu wajar/mengulanginya/ngaku salah' di {len(semua)} jadwal "
          f"Threads-uky: {len(muncul)} kemunculan, {len(jadi_topik)} jadi topik/baris pertama")
    for d in jadi_topik:
        print("   ", wib(d).strftime("%Y-%m-%d %H:%M"), d.get("type"),
              "|", (d.get("description") or "").strip().splitlines()[0][:70])

    # 2) slot & duplikat media
    hari = datetime(2026, 11, 16).date()
    same_day = [d for d in fetch_uky(c) if wib(d) and wib(d).date() == hari]
    print(f"Jadwal Threads-uky di {hari}: "
          f"{[(wib(d).strftime('%H:%M'), d.get('type')) for d in same_day]}")
    assert not same_day, f"slot {hari} tidak kosong - pilih hari lain"
    assert not media_hits(c, MEDIA_NAME, refresh=True), "media ini sudah punya jadwal"

    url, out = upload()
    print("LOCAL JPEG:", out, os.path.getsize(out), "bytes")
    print("PUBLIC URL:", url)
    codes = check_public(url)
    print("INTERNET-PATH CODES:", codes)
    if not any(v == "200" for v in codes.values()):
        print("STOP: URL publik tidak 200 - jangan schedule (aturan media server).")
        return 1

    res = c.create_schedule(
        UKY_T, cap, SLOT_AT,
        title=TITLE, topic=TOPIC, type_="image",
        medias=[{"url": url, "type": "image", "alt": FILENAME}],
        replies=[],
    )
    sid = res.get("scheduleId") or res.get("_id") or res.get("id")
    print("CREATE RESPONSE:", json.dumps(res)[:300], "-> SID:", sid)

    hits = media_hits(c, MEDIA_NAME, refresh=True)
    print(f"VERIFIKASI: {len(hits)} jadwal dgn media {MEDIA_NAME}")
    ok = False
    for d in hits:
        w = wib(d)
        desc = d.get("description") or ""
        print(f"  id={d.get('id')} status={d.get('status')} type={d.get('type')} "
              f"at={w.strftime('%Y-%m-%d %H:%M')} WIB topic={len(d.get('topic') or '')}c")
        print(f"  media={d['medias'][0]['url']}")
        print(f"  desc({len(desc)}) replies={len(d.get('replies') or [])} "
              f"newline_asli={NL2 in desc} literal={chr(92) + 'n' in desc}")
        if (d.get("id") == sid and d.get("status") in ("pending", "success")
                and NL2 in desc and (d.get("topic") or "") == TOPIC):
            ok = True
    if not (ok and len(hits) == 1):
        print("GAGAL verifikasi: harus 1 jadwal, sid cocok, topic utuh, newline asli")
        return 1
    print("OK TERVERIFIKASI: 1 jadwal, media + caption + topic terpasang")

    # 3) STATE + LOG
    lp = os.path.join(ROOT, "image_posting_log.json")
    sp = os.path.join(ROOT, "image_posting_state.json")
    log = json.load(open(lp))
    st = json.load(open(sp))
    now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.000Z")

    log.append({
        "timestamp": now,
        "item_id": ITEM_ID, "brand": "ukyhandoko", "source": "uky5_output",
        "filename": f"{FILENAME} (kartu square 1080x1080, varian PUTIH bg #FFFFFF + teks "
                    f"#122B63, standar 16 Sep - sesuai; seri uky5 kartu ke-5)",
        "topic": TOPIC,
        "slot_note": f"cron sempat jeda 20-25 Okt (tak ada log); lane image 08:00 sudah terisi "
                     f"s/d 14 Nov 2026 (item #91); 15 Nov ada post teks 10:06; {SLOT_WIB} = hari "
                     f"kosong total utk Threads-uky (dicek API: 0 jadwal 16 Nov), aturan Bos "
                     f"16 Okt '1 hari 1 postingan threads'.",
        "schedule_times": {"threads_uky": f"{SLOT_AT} ({SLOT_WIB}) - image 1"},
        "repliz_ids": {"threads_uky": sid},
        "caption_chars": len(cap), "media_url": url,
        "caption_final": cap, "replies": [], "link": "",
        "verifikasi": f"GET/re-list /public/schedule -> id {sid}, accountId {UKY_T} (Threads @ukyhandoko), "
                      f"type image, scheduleAt {SLOT_AT}, topic {len(TOPIC)} char, media {url} "
                      f"HTTP 200 ({codes}), status pending, replies 0",
        "hook_note": "opini (bold statement: tim yang ngaku salah lebih aman daripada yang "
                     "nggak pernah mengakui + tanya setuju/nggak; nada santai 5 Okt 2026); "
                     "entri kartu terakhir #90 sanjungan, #91 netral -> opini",
        "next_index": (st["index"] + 1) % st["total"],
        "seri_note": "Seri uky5 (14 kartu, gen_uky5_quotes.py), kartu ke-5 dari 14.",
    })
    st["index"] = (st["index"] + 1) % st["total"]
    json.dump(log, open(lp, "w"), indent=2, ensure_ascii=False)
    json.dump(st, open(sp, "w"), indent=2)
    print("STATE ->", st)
    print("LOG ->", lp, f"({len(log)} entri)")
    return 0


if __name__ == "__main__":
    sys.exit(main())
