#!/usr/bin/env python3
"""Update SEMUA caption jadwal pending Pak Otto: jam buka 06.00-21.00 → 10.00-21.00 WIB."""
import sys, json, urllib.request
sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from repliz_client import HEADERS, BASE

OTTO = {
    "6a86d6e962caae1e04ffedaa": "IG",
    "6a86d70362caae1e04ffedef": "TikTok",
    "6a8f9df162caae1e040754d8": "FB",
    "6a86d84b62caae1e04fff12c": "Threads",
}
OLD_PATTERNS = ["06.00 - 21.00", "06.00-21.00", "06:00 - 21:00", "06:00-21:00", "Buka Setiap Hari: 06.00", "10.00–21.00"]
NEW = "⏰ Buka Setiap Hari: 10.00 - 21.00 WIB"

def get(sid):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}", headers=HEADERS)
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)

def put(sid, payload):
    req = urllib.request.Request(f"{BASE}/public/schedule/{sid}",
                                 data=json.dumps(payload).encode(),
                                 headers={**HEADERS, "Content-Type": "application/json"},
                                 method="PUT")
    with urllib.request.urlopen(req, timeout=30) as r:
        return r.status

# kumpulkan semua pending
found = []
for accid, nm in OTTO.items():
    for p in range(1, 90):
        raw = urllib.request.Request(f"{BASE}/public/schedule?page={p}&limit=100", headers=HEADERS)
        with urllib.request.urlopen(raw, timeout=30) as r:
            docs = json.load(r)["docs"]
        for d in docs:
            if d.get("accountId") == accid and (d.get("status") or "").lower() == "pending":
                found.append((accid, nm, d))
print(f"total pending akun Pak Otto: {len(found)}")

import re
updated = skipped = 0
for accid, nm, d in found:
    desc = d.get("description") or ""
    new_desc = desc
    # pola jam lama dalam berbagai format
    new_desc = re.sub(r"06\.00\s*[-–]\s*21\.00", "10.00 - 21.00", new_desc)
    new_desc = re.sub(r"06[:.]00\s*[-–]\s*21[:.]00", "10.00 - 21.00", new_desc)
    new_desc = re.sub(r"Buka (Setiap )?Hari:? 10\.00 - 21\.00 WIB", NEW, new_desc)
    new_desc = re.sub(r"⏰? ?Buka (Setiap )?Hari: 06\.00 - 21\.00 WIB", NEW, new_desc)
    new_desc = new_desc.replace("Buka Setiap Hari: 10.00 - 21.00 WIB", NEW)
    # kalau masih ada 06.00 mentah
    if "06.00" in new_desc or "06:00" in new_desc:
        new_desc = re.sub(r"\b06\.00\b", "10.00", new_desc)
    if new_desc == desc:
        # cek apakah caption punya baris jam sama sekali
        if "21.00" in desc and "10.00" not in desc:
            print(f"  ⚠️ {nm} {d.get('scheduleAt')} | jam lain? | {(desc[:120]).replace(chr(10),' / ')}")
        skipped += 1
        continue
    payload = {
        "accountId": d.get("accountId"),
        "title": d.get("title", ""),
        "description": new_desc,
        "topic": d.get("topic", ""),
        "type": d.get("type", ""),
        "medias": d.get("medias") or [],
        "scheduleAt": d.get("scheduleAt"),
        "replies": d.get("replies") or [],
    }
    try:
        put(d["id"], payload)
        updated += 1
        print(f"  ✅ {nm:8s} | {d.get('scheduleAt')} | jam buka → 10.00-21.00")
    except Exception as e:
        print(f"  ❌ {d['id']}: {e}")

print(f"\n📊 Updated: {updated} | skipped: {skipped}")
