#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""cek_dek_tabel_kunci.py — deteksi deck carousel IG SS (kunci Okt) yang slide isinya
memuat sisa TABEL markdown atau seksi sampah (Baca juga / Artikel terkait).

Read-only: memakai fungsi generator kunci_car10_okt (parse_artikel + logika pemilihan seksi)
tanpa render & tanpa API. Dipakai untuk tahu deck mana yang perlu dirakit ulang.
"""
import re
import sys

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
import kunci_car10_okt as K  # noqa: E402

SAMPAH = re.compile(r"^(baca juga|artikel terkait|artikel terbaru|tags|arsip|kategori)", re.I)


def main():
    mulai = sys.argv[1] if len(sys.argv) > 1 else "2026-10-19"
    for tgl_s, slug, prefix, tag in K.MAPPING:
        if tgl_s < mulai:
            continue
        art = K.parse_artikel(slug)
        if not art:
            print(f"{tgl_s} {prefix:24s} ⛔ artikel gagal dibaca")
            continue
        seksi = art["seksi"]
        isi = [(h, K.kalimat(i)) for h, i in seksi]
        n = 4 if len(isi) <= 6 else 3
        unit = [(h, ks[:n], ks[n:]) for h, ks in isi]
        pilih = [(h, ks) for h, ks, _ in unit]
        if len(pilih) < 8:
            tambah, urut = {}, sorted(range(len(unit)), key=lambda i: -len(unit[i][2]))
            for i in urut:
                if len(pilih) + len(tambah) >= 8:
                    break
                if len(unit[i][2]) >= 2:
                    tambah[i] = unit[i][2][:n]
            pilih = []
            for i, (h, ks, sisa) in enumerate(unit):
                pilih.append((h, ks))
                if i in tambah:
                    pilih.append((h + " (lanjutan)", tambah[i]))
        masalah = []
        for idx, (h, ks) in enumerate(pilih[:8], start=2):
            teks = " ".join(ks)
            if "|" in teks or "|" in h:
                masalah.append(f"s{idx}=TABEL({h[:28]})")
            elif SAMPAH.search(h.strip()):
                masalah.append(f"s{idx}=SAMPAH({h[:28]})")
        tanda = "⚠️ " + " ".join(masalah) if masalah else "✅ bersih"
        print(f"{tgl_s} {prefix:24s} {tanda}")


if __name__ == "__main__":
    main()
