#!/usr/bin/env python3
"""Jadwalkan ULANG semua jadwal status `error` HARI INI (WIB) supaya tayang segera.

Resep resmi skill atun-social-automation: errored schedule TIDAK bisa di-resume —
harus DELETE lalu CREATE ulang dengan payload sama, scheduleAt baru.

Pemakaian:
    python3 reschedule_error_hari_ini.py            # dry-run (lihat rencana)
    python3 reschedule_error_hari_ini.py --go       # eksekusi

Aturan: maksimal 1 konten/hari/akun adalah default Bos, TAPI perintah eksplisit
"tayangkan segera" (21 Sep 2026) menang — item yang tadinya memang dijadwalkan hari ini
dianggap belum tayang, jadi digeser ke slot terdekat hari ini juga.
"""
import json
import sys
from datetime import datetime, timedelta, timezone

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

GO = "--go" in sys.argv
WIB = timezone(timedelta(hours=7))


def wib(s):
    return (datetime.fromisoformat(s.replace("Z", "+00:00")) + timedelta(hours=7)).replace(tzinfo=None)


def fetch_all(c):
    first = c.get_schedules(page=1, limit=100)
    total = first.get("totalDocs", 0)
    docs = list(first.get("docs", []))
    for p in range(2, (total + 99) // 100 + 1):
        docs.extend(c.get_schedules(page=p, limit=100).get("docs", []))
    return docs


def main():
    c = get_client()
    docs = fetch_all(c)
    today = datetime.now(WIB).date()
    targets = [d for d in docs
               if (d.get("status") or "").lower() == "error"
               and wib(d["scheduleAt"]).date() == today]
    targets.sort(key=lambda x: x["scheduleAt"])
    print(f"jadwal error HARI INI ({today}): {len(targets)}\n")

    # slot baru: mulai +20 menit dari sekarang, selang 3 menit
    base = datetime.now(timezone.utc).replace(second=0, microsecond=0) + timedelta(minutes=25)
    plan = []
    for i, d in enumerate(targets):
        at = base + timedelta(minutes=3 * i)
        plan.append((d, at))
        a = d.get("account") or {}
        print(f"  {wib(d['scheduleAt']):%H:%M} -> {at.astimezone(WIB):%H:%M} WIB | "
              f"{(a.get('name') or '?')[:34]:34} | {d.get('type'):5} | {d.get('id')} | tayang {d.get('title') or '-'}")

    if not GO:
        print("\n(dry-run — jalankan ulang dengan --go untuk eksekusi)")
        return

    print("\n=== EKSEKUSI ===")
    results = []
    for d, at in plan:
        a = d.get("account") or {}
        name = (a.get("name") or "?")[:34]
        try:
            dele = c.delete_schedule(d["id"])
        except Exception as e:
            print(f"❌ DELETE gagal {d['id']}: {e}")
            results.append((name, d["id"], None, f"delete gagal: {e}"))
            continue
        try:
            res = c.create_schedule(
                d["accountId"],
                d.get("description") or "",
                at.strftime("%Y-%m-%dT%H:%M:%S.000Z"),
                title=d.get("title") or "",
                topic=d.get("topic") or "",
                type_=d.get("type") or "text",
                medias=d.get("medias") or [],
                replies=d.get("replies") or [],
                meta=d.get("meta"),
                additional_info=d.get("additionalInfo"),
            )
        except Exception as e:
            print(f"❌ CREATE gagal {name}: {e}")
            results.append((name, d["id"], None, f"create gagal: {e}"))
            continue
        new_id = res.get("scheduleId") or res.get("_id") or res.get("id")
        # verifikasi read-back
        chk = {}
        try:
            chk = c.get_schedule(new_id) or {}
            chk = chk.get("doc") or chk
        except Exception as e:
            chk = {"status": f"verifikasi gagal: {e}"}
        print(f"✅ {name:34} | {d['id']} -> {new_id} | {at.astimezone(WIB):%H:%M} WIB | "
              f"status={chk.get('status')} | type={chk.get('type')} | medias={len(chk.get('medias') or [])}")
        results.append((name, d["id"], new_id, chk.get("status")))

    out = "/home/mantapman/.hermes/profiles/atun/workspace/log_reschedule_error_21sep.json"
    json.dump([{"akun": r[0], "lama": r[1], "baru": r[2], "status": r[3]} for r in results],
              open(out, "w"), indent=1, ensure_ascii=False)
    print(f"\nlog: {out}")
    ok = sum(1 for r in results if r[3] and "pending" in str(r[3]).lower())
    print(f"ringkasan: {ok}/{len(results)} berhasil dibuat & pending")


if __name__ == "__main__":
    main()
