#!/usr/bin/env python3
"""hc42: (1) cek detail hc41 media/status; (2) ambil isi artikel terpilih via WP REST."""
import json, sys, urllib.request, urllib.parse
sys.path.insert(0, '/home/mantapman/.hermes/profiles/atun/workspace')
from repliz_client import ACC
docs = json.load(open('/tmp/repliz_all_20260921.json'))

def text_of(d):
    return " ".join([(d.get('description') or ''), (d.get('title') or '')])

print("=== hc41 media ss_hc41_analytics_* di semua akun ===")
for d in docs:
    for m in (d.get('medias') or []):
        u = (m.get('url') or '')
        if 'ss_hc41' in u:
            print("  %s | %s | %s | %s | %s | %s" % (ACC.label(d.get('accountId')) if hasattr(ACC, 'label') else d.get('accountId'),
                  (d.get('scheduleAt') or '')[:16], d.get('status'), d.get('type'), (d.get('title') or '')[:40], u.split('/')[-1]))

print("\n=== data-analytics di Threads SS: semua ===")
for d in docs:
    if d.get('accountId') == ACC.STUDIOSOFT_THREADS and 'data-analytics-rumah-sakit' in text_of(d):
        print("  %s | %s | %s | medias=%d | %s" % ((d.get('scheduleAt') or '')[:16], d.get('status'), d.get('type'),
              len(d.get('medias') or []), (d.get('title') or '')[:45]))
        if d.get('status') == 'error':
            print("     ERR:", str(d.get('error') or d.get('errorMessage') or d.get('reason'))[:200])

print("\n=== iklan-facebook-rumah-sakit di FB SS (hc40) ===")
for d in docs:
    if d.get('accountId') == ACC.STUDIOSOFT_FB and 'iklan-facebook-rumah-sakit' in text_of(d):
        print("  %s | %s | %s" % ((d.get('scheduleAt') or '')[:16], d.get('status'), d.get('title')))

# ---- fetch artikel ----
SLUGS = ["panduan-seo-klinik-rumah-sakit", "iklan-facebook-rumah-sakit", "google-business-profile-klinik"]
for slug in SLUGS:
    url = ("https://studiosoft.id/wp-json/wp/v2/posts?slug=%s&_fields=date,slug,title,content,excerpt,link"
           % urllib.parse.quote(slug))
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    try:
        data = json.loads(urllib.request.urlopen(req, timeout=120).read().decode())
    except Exception as e:
        print("\n!! gagal fetch", slug, e)
        continue
    if not data:
        print("\n!! tidak ketemu", slug)
        continue
    p = data[0]
    open('/tmp/hc42_art_%s.json' % slug, 'w').write(json.dumps(p))
    print("\n### %s | %s | %s" % (p['slug'], p['date'], p['title']['rendered']))
