#!/usr/bin/env python3
"""hc42: tulis state + log + catatan harian (idempotent-ish; cek dulu biar tidak dobel)."""
import json, os, sys
from datetime import datetime, timezone, timedelta

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
wib = datetime.now(timezone(timedelta(hours=7)))
stamp = wib.strftime("%Y-%m-%d %H:%M")

TITLE = "Panduan SEO untuk Klinik dan Rumah Sakit: Biar Mudah Ditemukan Pasien di Google"
ARTICLE_URL = "https://studiosoft.id/panduan-seo-klinik-rumah-sakit/"
LI_TITLE = "Iklan Facebook & Instagram untuk Rumah Sakit: Etis, Efektif, dan Sesuai Regulasi"
FB_TITLE = "Google Business Profile untuk Klinik: Cara Biar Pasien Gampang Nemu Lokasi Anda"

ALBUM = "6ab1062202078a414acbaa45"
REPLY1_ID = "6ab106323032e3a79cf13dd0"
REPLY2_ID = "6ab1063602078a414acbb0d3"
LI_ID = "6ab104d202078a414acb4216"
FB_ID = "6ab104dc3032e3a79cf0cc47"

# 1) state
p = WS + "/studiosoft_healthcare_state.json"
st = json.loads(open(p).read())
if st.get("index") == 37:
    st["index"] = 38
    st["topic"] = TITLE
    st["last_post"] = stamp
    json.dump(st, open(p, "w"))
    print("state ->", st)
else:
    print("state sudah:", st, "(tidak diubah)")

# 2) log
logp = WS + "/studiosoft_healthcare_log.txt"
log = open(logp).read()
if "hc42" not in log[-3000:]:
    line = ("\n[%s WIB] hc42 (TOPIK BARU di Threads: panduan SEO untuk klinik/RS \u2014 0 jadwal di "
            "Threads SS, jadi bukan re-air) | %s | %s | Threads album %s (22 Sep 2026 09:00 WIB / "
            "2026-09-22T02:00Z) + 2 replies (%s, %s) | LinkedIn TEXT \"%s\" 10 Okt 2026 11:00 WIB "
            "(2026-10-10T04:00:00.000Z) | FB TEXT \"%s\" (tanpa media, replies=[]) 21 Sep 2026 19:30 "
            "WIB (2026-09-21T12:30:00.000Z) | catatan: stok artikel healthcare baru masih HABIS "
            "(WP REST 21 Sep: artikel terbaru 20 Sep `jasa-branding-surabaya-membangun-identitas-brand-kuat` "
            "= non-healthcare); audit 2.820 jadwal Repliz -> `panduan-seo-klinik-rumah-sakit` BELUM PERNAH "
            "ada di Threads SS -> carousel BARU ss_hc42_seoklinik_* + engine ss_carousel_lib (bg #122B63, "
            "JPEG q85, 94-111 KB); LinkedIn pakai artikel iklan-facebook-rumah-sakit (FREE di LI SS); FB "
            "pakai artikel google-business-profile-klinik (di FB SS hanya pernah ERROR 29 Agu). PITFALL: "
            "(a) album Threads gagal create pertama kali dgn HTTP 500 'Cannot read properties of undefined "
            "(reading 0)' -> retry sukses (hc42_retry_threads.py); (b) ingress funnel 103.84.155.217 sering "
            "lambat 21-30s -> verify_urls timeout 60s; (c) album Threads hc41 (20 Sep) gagal 'media could "
            "not be fetched' karena HOST OFF ~33 jam (20 Sep 00:56Z-21 Sep 09:40Z), bukan bug Repliz. "
            "state index -> 38.\n"
            % (stamp, TITLE, ARTICLE_URL, ALBUM, REPLY1_ID, REPLY2_ID, LI_TITLE, FB_TITLE))
    open(logp, "a").write(line)
    print("log ditulis")
else:
    print("log sudah ada hc42")

# 3) catatan harian
cp = WS + "/catatan/2026-09-21.md"
note = open(cp).read()
if "hc42" in note:
    print("catatan sudah ada bagian hc42")
else:
    sec = """

---

## 🏥 Seri Healthcare StudioSoft — run hc42 (cron `studiosoft-healthcare-carousel-harian`)

Dijalankan manual 21 Sep (cron 02:00 WIB sempat tidak jalan karena host OFF 20–21 Sep).
Hasil: **3 platform terjadwal & terverifikasi lewat fetch ulang per-ID dari API.**

- **📱 Threads SS** — carousel 5 slide `ss_hc42_seoklinik_*` + 2 replies · slot **22 Sep 09:00 WIB**
  (`2026-09-22T02:00:00.000Z`) · album `%s` pending · replies `%s`, `%s`
- **💼 LinkedIn SS** — TEXT 1.641 char (artikel iklan FB/IG RS) · slot **10 Okt 11:00 WIB**
  (`2026-10-10T04:00:00.000Z`) · `%s` pending · medias=0 replies=0
- **🔵 Facebook SS** — TEXT 1.425 char, tanpa media, `replies=[]` · slot **21 Sep 19:30 WIB**
  (`2026-09-21T12:30:00.000Z`) · `%s` pending

- **Topik Threads = TOPIK BARU, bukan re-air:** audit 2.820 jadwal Repliz menunjukkan
  `panduan-seo-klinik-rumah-sakit` **0 jadwal** di Threads SS sepanjang sejarah akun
  (sisa kandidat healthcare lain sudah tayang semua). Slide dibuat ulang dari isi artikel
  (keyword intent kesehatan, local SEO, fondasi teknis) — standar Bos 16 Sep: engine
  `ss_carousel_lib.py`, bg `#122B63`, rata kiri, blok tengah vertikal, tanpa separator,
  bullet dot, judul 85 / body 36 / sub 30. Diverifikasi visual (2 slide dilihat langsung).
- **Stok artikel healthcare baru masih HABIS** — WP REST 21 Sep: artikel terbaru
  20 Sep `jasa-branding-surabaya-membangun-identitas-brand-kuat` (non-healthcare).
  → seri hc butuh artikel healthcare baru dari Bos, atau lanjut pola re-air (nama file slide WAJIB baru).
- **LinkedIn:** artikel `iklan-facebook-rumah-sakit` — status FREE di LinkedIn SS (tidak ada jadwal apa pun).
- **Facebook:** artikel `google-business-profile-klinik` — di FB SS hanya pernah `error` (29 Agu),
  jadi belum pernah tayang sebagai teks. `replies=[]` (aturan FB).

### ⚠️ Temuan teknis run ini (masuk pelajaran)

1. **Album Threads gagal create pertama kali** → `HTTP 500 {"message":"Cannot read properties of
   undefined (reading '0')"}` dari Repliz (server-side, bukan payload kita — LinkedIn & FB sukses di
   run yang sama). **Retry ke-2 sukses** → mitobat baru: `hc42_retry_threads.py` (retry album 4x,
   guard idempotensi, reply ikut dibuat setelah album hidup).
2. **Ingress funnel `103.84.155.217` sering lambat 21–30 s** (kadang timeout 30 s) sementara
   `103.84.155.153` ~1 s. Verifikasi media `timeout 60s + 4 percobaan`; JPEG dikecilkan ke
   quality 85 (94–111 KB) supaya fetch lebih cepat.
3. **hc41 (20 Sep 02:00Z) album Threads `ss_hc41_analytics_*` GAGAL lagi** — "The media could not be
   fetched from this URI" **padahal media 200 di kedua ingress sekarang**. Penyebab sebenarnya:
   **host OFF ~33 jam (20 Sep 00:56Z – 21 Sep 09:40Z)** — jadi bukan bug Repliz dan bukan salah nama
   file. Topik data-analytics masih belum pernah tayang dalam bentuk carousel → kandidat re-air
   berikutnya (nama file slide harus baru, mis. `ss_hc43_*`).
4. Pitfall verifikasi (sudah ada di skill): field `replies` di endpoint LIST balik sebagai dict
   per-karakter (`{'0':'6','1':'a',...,'status':'pending'}`) → **abaikan key non-numerik** saat
   join, kalau tidak reply dikira tidak menempel.

Referensi script: `studiosoft_hc42_carousel_gen.py` · `studiosoft_healthcare_cron_run_hc42.py` ·
`hc42_retry_threads.py` · `verify_hc42.py` · `hc42_analyze.py` · `hc42_check_fb.py`.
""" % (ALBUM, REPLY1_ID, REPLY2_ID, LI_ID, FB_ID)
    open(cp, "a").write(sec)
    print("catatan ditambahkan")
