#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cermin konten TS Law (Threads/IG/FB) ke LinkedIn — perintah Bos 13 Okt 2026:
"untuk konten yang lain tolong juga di share ke semua sosmed TSlaw".

Cara kerja: cari jadwal TS Law pada rentang tanggal (WIB) di Threads/IG/FB, lalu untuk
tiap item yang belum punya kembaran di LinkedIn (dicocokkan dari URL media, atau judul+caption
untuk post teks) buat jadwal LinkedIn-nya di jam yang sama, digeser 1 jam lebih awal
(biar tidak bentrok dengan slot 09:00 Threads).

Pakai: /usr/bin/python3 cermin_tslaw_linkedin.py 2026-10-14 2026-10-20          (dry run)
       /usr/bin/python3 cermin_tslaw_linkedin.py 2026-10-14 2026-10-20 --run    (eksekusi)
"""
import hashlib
import json
import sys
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE, get_client  # noqa: E402

LINKEDIN = "6a60101562caae1e04e901ac"
IG = "6a76a54d62caae1e04f30968"
FB = "6a3b41d1c5ff4ce3a32753e8"
THREADS = "6a35f8b7c5ff4ce3a322b2ed"
SUMBER = {IG: "IG", FB: "FB", THREADS: "Threads"}
WIB = timezone(timedelta(hours=7))


def semua_jadwal():
    docs, page = [], 1
    while True:
        q = urllib.parse.urlencode({"page": page, "limit": 100})
        req = urllib.request.Request(f"{BASE}/public/schedule?{q}", headers=HEADERS)
        with urllib.request.urlopen(req, timeout=60) as r:
            d = json.load(r)
        docs += d.get("docs", d.get("data", []))
        if not d.get("hasNextPage") or not docs:
            break
        page += 1
    return docs


def kunci(s):
    """Kunci pembanding: URL media kalau ada, kalau tidak hash judul+caption."""
    med = s.get("medias") or []
    urls = [m.get("url") for m in med if m.get("url")]
    if urls:
        return "media:" + "|".join(sorted(u.split("/")[-1] for u in urls))
    teks = ((s.get("title") or "") + "::" + (s.get("description") or "")).strip()
    return "teks:" + hashlib.sha1(teks.encode()).hexdigest()[:16]


def main():
    if len(sys.argv) < 3:
        sys.exit(__doc__)
    awal, akhir = sys.argv[1], sys.argv[2]
    mode = "run" if "--run" in sys.argv else "dry"
    lo = datetime.fromisoformat(awal + "T00:00:00+07:00").astimezone(timezone.utc)
    hi = datetime.fromisoformat(akhir + "T23:59:59+07:00").astimezone(timezone.utc)

    docs = semua_jadwal()
    kunci_linkedin = {kunci(s) for s in docs if s.get("accountId") == LINKEDIN}

    kandidat = []
    for s in docs:
        if s.get("accountId") not in SUMBER:
            continue
        if str(s.get("type")) == "story":  # story tidak ada di LinkedIn
            continue
        try:
            t = datetime.fromisoformat(str(s.get("scheduleAt")).replace("Z", "+00:00"))
        except Exception:
            continue
        if not (lo <= t <= hi):
            continue
        if kunci(s) in kunci_linkedin:
            continue
        kandidat.append((t, SUMBER[s["accountId"]], s))

    kandidat.sort(key=lambda x: x[0])
    print(f"kandidat cermin {awal}..{akhir}: {len(kandidat)} item (mode {mode})")
    cl = get_client()
    for t, plat, s in kandidat:
        med = (s.get("medias") or [{}])[0]
        url = med.get("url") or ""
        tipe = str(s.get("type") or "text")
        if tipe == "album":
            print(f"  ⚠️ {plat} {t.astimezone(WIB).strftime('%d %b %H:%M')} WIB: {tipe} ({len(s.get('medias') or [])} media) "
                  f"→ carousel LinkedIn butuh berkas PDF/dokumen, dilewati")
            continue
        at = (t - timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
        print(f"  {'✅' if mode == 'run' else '[DRY]'} {plat} {t.astimezone(WIB).strftime('%d %b %H:%M')} WIB "
              f"→ LinkedIn {datetime.fromisoformat(at.replace('Z', '+00:00')).astimezone(WIB).strftime('%d %b %H:%M')} WIB "
              f"| {tipe} | {(url.split('/')[-1] or '-')[:45]}")
        if mode != "run":
            continue
        res = cl.create_schedule(LINKEDIN, s.get("description") or "", at,
                                 title=(s.get("title") or "TS Law") + " (LinkedIn)",
                                 topic=s.get("topic") or "Edukasi Hukum", type_=tipe,
                                 medias=[{"url": url, "type": tipe, "alt": med.get("alt") or ""}] if url else [],
                                 replies=[])
        sid = res.get("scheduleId") or res.get("_id") or res.get("id")
        back = cl.get_schedule(sid)
        print(f"     id={sid} | status={back.get('status')} | {back.get('type')} | "
              f"{(back.get('medias') or [{}])[0].get('url', '').split('/')[-1]}")


if __name__ == "__main__":
    main()
