#!/usr/bin/env python3
"""DAILY IMAGE POSTING — cron 2026-10-18T18:00Z (= 19 Okt 2026 01:00 WIB).

Item antrean #90 = uky_quote5_perjanjian_jelas (seri uky5, kartu ke-3 dari 14).
KARTU: square 1080x1080, varian ORANGE (bg #F97316 / RGB 249,115,22 + teks putih) —
rotasi BIRU/PUTIH/ORANGE seri uky5, rata kiri, satu blok tengah vertikal, tanpa separator/glyph.

NADA (Bos 5 Okt 2026): santai ("aku"/"kamu"), 0 hashtag, 0 mention internal, tanpa link,
replies=[] -> pancingan diskusi di ekor (sanjungan: 2 entri kartu terakhir netral + opini,
tipe sanjungan paling sedikit terpakai).
topic (topic_tag Threads) WAJIB <=45 char.

SLOT: lane kartu uky penuh tiap hari sampai 11 Nov 2026 08:00. 12 Nov sudah ada post teks
10:06 (aturan Bos 16 Okt "1 hari 1 postingan threads") -> hari kosong pertama 13 Nov 2026.
"""
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_perjanjian_jelas"
FILENAME = "perjanjian_jelas_orange.png"
SRC = os.path.join(ROOT, "uky5_output", FILENAME)
MEDIA_NAME = "uky_quote5_perjanjian_jelas.jpg"
TITLE = "Perjanjian Jelas Itu Bentuk Saling Menghormati"
TOPIC = "Perjanjian jelas, hubungan awet"     # 31 char (<=45)

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

BODY = (
    "Detail kerjaan aku tulis jelas di awal, bukan karena nggak percaya klien. "
    "Justru biar dua-duanya tenang. \u2705"
    + NL2 +
    "Aku pernah kerja cuma modal \u201csama-sama enak\u201d, tanpa perjanjian tertulis. "
    "Ujungnya satu ngerasa nambah kerjaan, satu ngerasa nggak pernah minta. "
    "Dua-duanya nggak salah, cuma nggak ada yang pegang kesepakatan yang sama."
)

HOOK = ("Buat yang sudah biasa nulis lingkup kerja di awal, kamu sudah jaga hubungan sebelum "
        "masalahnya muncul. \U0001F44F Apa satu hal yang selalu kamu tulis di perjanjian?")

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"perjanjian|kesepakatan|lingkup kerja|kontrak kerja|saling menghormati", 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")
    return None if not at else datetime.fromisoformat(at.replace("Z", "+00:00")) + 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 == (249, 115, 22), f"bg {bg} bukan ORANGE (249,115,22) - rotasi seri uky5"
    assert (255, 255, 255) in dom, f"teks bukan putih: {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 #90")

    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 'perjanjian/kesepakatan/lingkup kerja' 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, 13).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 ORANGE bg #F97316 + teks "
                    f"putih, standar 16 Sep - sesuai; seri uky5 kartu ke-3)",
        "topic": TOPIC,
        "slot_note": f"lane kartu uky penuh s/d 11 Nov 2026 08:00 (item #89); 12 Nov sudah ada "
                     f"post teks 10:06; {SLOT_WIB} hari kosong total utk Threads-uky "
                     f"(dicek API: 0 jadwal 13 Nov), aturan Bos 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": "sanjungan (apresiasi ke yang sudah nulis lingkup kerja di awal + tetap tanya "
                     "satu hal yang selalu ditulis; nada santai 5 Okt 2026); entri kartu terakhir "
                     "#88 netral, #89 opini -> sanjungan paling sedikit terpakai",
        "next_index": (st["index"] + 1) % st["total"],
        "seri_note": "Seri uky5 (14 kartu, gen_uky5_quotes.py), kartu ke-3 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())
