#!/usr/bin/env python3
"""Verifikasi final 19 Okt 2026: baca ulang dari API, audit jadwal yang baru dibuat."""
import re, sys
from datetime import datetime, timedelta, timezone

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

WIB = timezone(timedelta(hours=7))
CJK = re.compile(r"[\u3000-\u9fff\uff00-\uffef]")
URL = re.compile(r"https?://\S+")
NEW = {
    "uky": ("6ad533ea83496b501fe7a5ac", 14),
    "tslaw": ("6ad5340883496b501fe7b001", 17),
    "tsc": ("6ad533ea83496b501fe7a5bf", 20),
    "das": ("6ad533ea83496b501fe7a5cb", 20),
}
TH = {"studiosoft": ACC.STUDIOSOFT_THREADS, "uky": ACC.UKY_THREADS,
      "tslaw": ACC.TSLAW_THREADS, "tsc": ACC.TSC_THREADS, "das": ACC.DAS_THREADS}

cli = get_client()
docs = []
for p in range(1, 60):
    r = cli.get_schedules(page=p, limit=100)
    b = r.get("docs", [])
    docs += b
    if len(b) < 100:
        break
print("total jadwal:", len(docs))

by_id = {d.get("_id"): d for d in docs}
print("\n== AUDIT JADWAL BARU 2026-10-19")
bad = 0
for name, (sid, hour) in NEW.items():
    d = by_id.get(sid)
    if not d:
        print(f"  ❌ {name}: id {sid} TIDAK ADA di API")
        bad += 1
        continue
    desc = d.get("description") or ""
    dt = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    reps = d.get("replies") or []
    checks = {
        "pending": d.get("status") == "pending",
        "type text": d.get("type") == "text",
        "jam benar": (dt.strftime("%Y-%m-%d"), dt.hour) == ("2026-10-19", hour),
        "<=500": len(desc) <= 500,
        "ada link": bool(URL.search(desc)),
        "link domain sendiri": (
            ("studiosoft.id" in desc) if name in ("uky", "studiosoft")
            else ("tslaw.id" in desc) if name == "tslaw"
            else ("theskincodeclinic.com" in desc) if name == "tsc"
            else ("dasindonesia.com" in desc)
        ),
        "no mention": not re.search(r"(?<!\S)@\w+", desc),
        "no CJK": not CJK.search(desc),
        "replies 0": not reps,
        "CTA komentar": bool(re.search(r"komentar|tulis di|ceritakan", desc[-170:], re.I)),
        "topic <=50": len(d.get("topic") or "") <= 50,
    }
    fails = [k for k, v in checks.items() if not v]
    bad += len(fails)
    print(f"  {'✅' if not fails else '❌'} {name:5s} {dt:%Y-%m-%d %H:%M} {d.get('status')} "
          f"len={len(desc)} topic={d.get('topic')!r} {'; '.join(fails) if fails else 'semua cek lolos'}")

print("\n== SEMUA JADWAL 19 OKT 2026 (per akun)")
for name, aid in TH.items():
    rows = []
    for d in docs:
        if d.get("accountId") != aid or not d.get("scheduleAt"):
            continue
        dt = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
        if dt.strftime("%Y-%m-%d") == "2026-10-19":
            rows.append((dt, d))
    rows.sort(key=lambda x: x[0])
    print(f"  {name}: {len(rows)} jadwal")
    for dt, d in rows:
        urls = URL.findall(d.get("description") or "")
        print(f"     {dt:%H:%M} {d.get('status'):8s} {d.get('type'):6s} {d.get('topic')!r} "
              f"{'LINK=' + urls[0] if urls else 'tanpa-link'}")

print("\n== DAS 5 hari ke depan (cek bank percakapan)")
rows = []
for d in docs:
    if d.get("accountId") != ACC.DAS_THREADS or not d.get("scheduleAt"):
        continue
    dt = datetime.fromisoformat(d["scheduleAt"].replace("Z", "+00:00")).astimezone(WIB)
    if "2026-10-19" <= dt.strftime("%Y-%m-%d") <= "2026-10-23":
        rows.append((dt, d))
for dt, d in sorted(rows, key=lambda x: x[0]):
    print(f"     {dt:%Y-%m-%d %H:%M} {d.get('status'):8s} {d.get('type'):6s} {(d.get('title') or '')[:50]}")

print("\nTOTAL MASALAH:", bad)
