#!/usr/bin/env python3
"""Offboarding Apotek Pamekasan: cek akun/jadwal Repliz, dan siapkan daftar yang harus dibersihkan."""
import json, re, sys
from collections import Counter

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

NAMA = {getattr(ACC, n): n for n in dir(ACC) if not n.startswith("_")}
client = get_client()

print("=== 1. akun Repliz yang berkaitan dengan apotek/pamekasan ===")
d = client.get("/public/account?page=1&limit=100")
docs = d.get("docs", []) if isinstance(d, dict) else []
temuan = [a for a in docs if re.search(r"apotek|pamekasan|arek", str(a.get("name") or ""), re.I)]
if temuan:
    for a in temuan:
        print(f"   {a['_id']} | {a.get('name')} | platform {a.get('platform')} | ACC: {NAMA.get(a['_id'], '?')}")
else:
    print("   (tidak ada akun apotek di Repliz)")

print("\n=== 2. jadwal Repliz untuk akun tersebut ===")
ids = {a["_id"] for a in temuan} | {getattr(ACC, n) for n in dir(ACC) if not n.startswith("_")
                                  and re.search(r"apotek|pamekasan|arek", n, re.I)}
semua = []
page = 1
while True:
    dd = client.get_schedules(page=page, limit=100)
    rows = dd.get("docs", []) if isinstance(dd, dict) else []
    semua += rows
    if len(rows) < 100:
        break
    page += 1
milik = [s for s in semua if s.get("accountId") in ids]
print(f"   total jadwal terbaca: {len(semua)} | milik akun apotek: {len(milik)}")
if milik:
    print("   rincian status:", dict(Counter(s.get("status") for s in milik)))
    for s in milik[:6]:
        print(f"      {s.get('status'):<8} {str(s.get('scheduleAt'))[:16]} | {str(s.get('description'))[:50]}")

print("\n=== 3. rujukan di cron & konfigurasi kerja ===")
for f in ("/home/mantapman/.hermes/cron/jobs.json",
          "/home/mantapman/.hermes/profiles/atun/cron/jobs.json"):
    try:
        j = json.load(open(f))
        for job in (j.get("jobs") or []):
            teks = json.dumps(job).lower()
            if "apotekpamekasan" in teks or "pamekasan" in teks:
                print(f"   {f.split('/')[-2]} | job: {job.get('name')} | {job.get('id')} | aktif={job.get('enabled')}")
    except Exception as e:
        print("   gagal baca", f, str(e)[:50])

for f in (f"{WS}/kpi_konfigurasi_klien.py", f"{WS}/drafts/cron_literatur.txt"):
    try:
        isi = open(f).read()
        n = len(re.findall(r"pamekasan", isi, re.I))
        print(f"   {f.split('/')[-1]:<28} sebutan 'pamekasan': {n}")
    except Exception as e:
        print(f"   {f}: {str(e)[:50]}")
