#!/usr/bin/env python3
"""Deteksi background navy lama (#0D4761 / #1E40AF) pada media pending THREADS & LINKEDIN."""
import json
import os
from collections import defaultdict
from datetime import datetime, timezone

from PIL import Image

DOCS = json.load(open("/tmp/ss_audit_all.json"))
IMG_DIR = "/home/mantapman/.hermes/profiles/atun/workspace/openclaw-img"
URL_PREFIX = "mantapserver.tail3947bb.ts.net/openclaw-img/"

THREADS_LI = {  # namanya mengandung THREADS atau LINKEDIN
    "6a334e89c5ff4ce3a3225a48": "UKY_THREADS",
    "6a335b9ec5ff4ce3a3225c2a": "STUDIOSOFT_THREADS",
    "6a334c49c5ff4ce3a32259c9": "STUDIOSOFT_LINKEDIN",
    "6a35f8b7c5ff4ce3a322b2ed": "TSLAW_THREADS",
    "6a4bbc5920e4f4f195e52960": "TSC_THREADS",
    "6a44ed1920e4f4f195d8ecf7": "EVERYBE_THREADS",
    "6a5f4af462caae1e04e8b9a6": "LEIT_THREADS",
    "6a86d84b62caae1e04fff12c": "SOTO_THREADS",
    "6a39e461c5ff4ce3a3233e09": "DAS_THREADS",
    "6a60451662caae1e04e91040": "LEIT_LINKEDIN",
    "6a60101562caae1e04e901ac": "TSLAW_LINKEDIN",
    "6a350ecbc5ff4ce3a32299ce": "DMARK_LINKEDIN",
}

TARGET_BG = {(13, 71, 97): "#0D4761", (30, 64, 175): "#1E40AF"}


def bg_variants(im):
    """Ambil beberapa titik sudut/tepi untuk menebak warna background."""
    w, h = im.size
    pts = [(4, 4), (w - 5, 4), (4, h - 5), (w - 5, h - 5), (w // 2, 4), (w // 2, h - 5)]
    return [im.getpixel(p) for p in pts]


now = datetime.now(timezone.utc)
seen = {}
for s in DOCS:
    aid = s.get("accountId")
    if aid not in THREADS_LI:
        continue
    if (s.get("status") or "").lower() not in ("pending", "scheduled", "draft"):
        continue
    sa = s.get("scheduleAt") or ""
    try:
        if datetime.fromisoformat(sa.replace("Z", "+00:00")) < now:
            continue
    except Exception:
        continue
    for m in (s.get("medias") or []):
        url = m.get("url") or ""
        if URL_PREFIX not in url:
            continue
        fn = os.path.basename(url.split("?")[0])
        if fn in seen:
            continue
        p = os.path.join(IMG_DIR, fn)
        if not os.path.exists(p):
            seen[fn] = (THREADS_LI[aid], "FILE HILANG", "")
            continue
        try:
            im = Image.open(p).convert("RGB")
            cols = bg_variants(im)
            hit = None
            for c in cols:
                for t, name in TARGET_BG.items():
                    if all(abs(c[i] - t[i]) <= 6 for i in range(3)):
                        hit = name
                        break
                if hit:
                    break
            top = max(set(cols), key=cols.count)
            seen[fn] = (THREADS_LI[aid], hit or "-", "#%02X%02X%02X" % top)
        except Exception as e:
            seen[fn] = (THREADS_LI[aid], "ERR", str(e)[:40])

by_acc = defaultdict(list)
for fn, (acc, hit, top) in seen.items():
    by_acc[acc].append((fn, hit, top))

print("=== MEDIA PENDING THREADS/LINKEDIN — deteksi bg navy lama ===")
tot_hit = 0
for acc in sorted(by_acc):
    items = sorted(by_acc[acc])
    hits = [i for i in items if i[1] in ("#0D4761", "#1E40AF")]
    tot_hit += len(hits)
    print("\n%s: %d file unik, %d kena ganti" % (acc, len(items), len(hits)))
    for fn, hit, top in items:
        mark = "  <<< GANTI" if hit in ("#0D4761", "#1E40AF") else ""
        print("   %-46s bg=%s warna=%s%s" % (fn, hit, top, mark))
print("\nTOTAL file yang perlu diubah: %d" % tot_hit)
json.dump({k: v for k, v in seen.items()}, open("/tmp/navy_media.json", "w"), indent=1)
