#!/usr/bin/env python3
"""Kumpulkan SEMUA link di jadwal Threads 5 akun (semua status) + same-day report. Read-only."""
import sys, re, json
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))
client = get_client()

ACC_MAP = {
    "studiosoft": (ACC.STUDIOSOFT_THREADS, "studiosoft.id"),
    "uky": (ACC.UKY_THREADS, "studiosoft.id"),
    "tslaw": (ACC.TSLAW_THREADS, "tslaw.id"),
    "tsc": (ACC.TSC_THREADS, "theskincodeclinic.com"),
    "das": (ACC.DAS_THREADS, "dasindonesia.com"),
}
URL_RE = re.compile(r"https?://[^\s\)\]]+")

all_docs = []
for p in range(1, 200):
    got = None
    for i in range(10):
        try:
            got = client.get_schedules(page=p, limit=100)
            break
        except Exception:
            print(f"retry page {p}", file=sys.stderr)
    if got is None:
        raise SystemExit("gagal fetch")
    b = got.get("docs", [])
    if not b:
        break
    all_docs.extend(b)
    if len(b) < 100:
        break

def norm(u):
    u = u.strip().rstrip('.,').lower()
    u = re.sub(r'^https?://(www\.)?', '', u)
    return u.rstrip('/')

DATE = "2026-10-06"
out = {}
for name, (aid, dom) in ACC_MAP.items():
    docs = [d for d in all_docs if d.get("accountId") == aid]
    used = set()
    for d in docs:
        txt = (d.get("description") or "")
        for r in (d.get("replies") or []):
            if isinstance(r, dict):
                txt += " " + (r.get("text") or "")
        for u in URL_RE.findall(txt):
            used.add(norm(u))
    same = []
    for d in docs:
        sa = d.get("scheduleAt")
        if not sa:
            continue
        try:
            dt = datetime.fromisoformat(str(sa).replace("Z", "+00:00")).astimezone(WIB)
        except Exception:
            continue
        if dt.strftime("%Y-%m-%d") == DATE:
            same.append(dt)
    same.sort()
    out[name] = {"used": sorted(used), "same_day_hours": [d.hour for d in same],
                 "n_docs": len(docs)}
    print(f"\n=== {name} — {len(docs)} jadwal, {len(used)} URL unik terpakai ===")
    print(f"  same-day {DATE}: {[d.strftime('%H:%M') for d in same]}")
    print(f"  URLs terpakai (domain sendiri):")
    for u in sorted(used):
        if dom in u:
            print(f"    - {u}")

json.dump(out, open("/tmp/threads_used_6okt.json", "w"), ensure_ascii=False, indent=1)
print("\nsaved /tmp/threads_used_6okt.json")
