#!/usr/bin/env python3
"""Riset sinyal viral 30 Sep 2026 — tren ID + berita per niche akun Threads."""
import subprocess, re, xml.etree.ElementTree as ET

UA = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36"


def curl(url, timeout=40):
    p = subprocess.run(["curl", "-4", "-sL", "--compressed", "--max-time", str(timeout), "-A", UA, url],
                       capture_output=True, text=True, errors="replace")
    return p.stdout or ""


def rss_items(xml, maks=12):
    out = []
    try:
        root = ET.fromstring(xml)
    except Exception:
        return out
    for it in root.iter("item"):
        t = it.findtext("title") or ""
        d = it.findtext("pubDate") or ""
        s = it.findtext("source") or ""
        out.append((re.sub(r"\s+", " ", t).strip(), d[:16], s))
        if len(out) >= maks:
            break
    return out


print("=" * 70)
print("A. GOOGLE TRENDS INDONESIA (trending sekarang)")
print("=" * 70)
for t, d, s in rss_items(curl("https://trends.google.com/trending/rss?geo=ID"), 15):
    print(f"  - {t}  ({s or 'trends'})")

print()
print("=" * 70)
print("B. TREN X INDONESIA (trends24.in)")
print("=" * 70)
html = curl("https://trends24.in/indonesia/")
tops = re.findall(r'<a[^>]*class="trend-link"[^>]*>(.*?)</a>', html)
if not tops:
    tops = re.findall(r'data-trend-name="([^"]+)"', html)
bersih = []
for t in tops:
    t = re.sub(r"<[^>]+>", "", t).strip()
    if t and t not in bersih:
        bersih.append(t)
print("  " + " | ".join(bersih[:25]) if bersih else "  (gagal parse)")

NICHE = {
    "HUKUM (TS Law)": ["warisan", "perceraian", "hukum pidana", "sengketa tanah", "utang piutang"],
    "SKIN/KLINIK (TSC)": ["jerawat", "skincare", "klinik kecantikan"],
    "OTOMOTIF (DAS)": ["servis mobil", "bengkel mobil", "mesin mobil"],
    "SEHAT/KEWANITAAN (EveryBe)": ["kesehatan wanita", "kebugaran", "nyeri sendi"],
    "WEB/SEO/AI (StudioSoft-uky)": ["SEO website", "UMKM digital", "AI untuk bisnis"],
}
for nama, queries in NICHE.items():
    print()
    print("=" * 70)
    print(f"C. {nama} — berita 3 hari terakhir (Google News)")
    print("=" * 70)
    for q in queries:
        url = f"https://news.google.com/rss/search?q={q.replace(' ', '+')}+when:3d&hl=id&gl=ID&ceid=ID:id"
        items = rss_items(curl(url), 5)
        print(f"  [{q}] {len(items)} hasil")
        for t, d, s in items:
            print(f"     - {t[:110]}  ({s})")
