#!/usr/bin/env python3
"""
clear_all_web_cache.py — Clear cache semua web klien (via curl, terbukti andal di host ini).
Metode per situs:
1. Refetch homepage + wp-json dengan cache-buster (flush CDN/server cache).
2. Coba purge header LiteSpeed (kalau server ini LiteSpeed — header diterima diam-diam).
3. Verifikasi HTTP 200.
Gunakan curl subprocess — cURL terbukti jalan (urllib bermasalah di host ini).
"""
import subprocess, time, json

SITES = [
    # (nama, url)
    ("Yasma Natura",    "https://yasmanatura.co.id"),
    ("Nucleasoft",      "https://otomasibisnispintar.com"),
    ("DMark",           "https://dmark.id"),
    ("Arlan",           "https://apotekpamekasan.com"),
    ("StudioSoft",      "https://studiosoft.id"),
    ("DAS",             "https://dasindonesia.com"),
    ("TSC",             "https://theskincodeclinic.com"),
    ("SSC",             "https://surabaya-skincentre.com"),
    ("EveryBe",         "https://everybeofficial.com"),
    ("TSLaw",           "https://tslaw.id"),
    ("RSIA",            "https://rsia.kendangsari.com"),
    ("Abimata",         "https://abimataconsultant.com"),
    ("LEIT",            "https://leit.co.id"),
    ("Eka Duta Jaya",   "https://ekaduta.com"),
]

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/125 Safari/537.36"

def curl(url, extra=None, timeout=25):
    """Return (code, ms). extra = list of curl args."""
    cmd = ["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}|%{time_total}",
           "-m", str(timeout), "-A", UA, "--http1.1"]
    if extra:
        cmd += extra
    cmd.append(url)
    try:
        out = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout + 10)
        raw = out.stdout.strip()
        if "|" in raw:
            code, t = raw.split("|", 1)
            return int(code), float(t)
        return None, 0.0
    except Exception:
        return None, 0.0

def main():
    print("=" * 62)
    print("CLEAR CACHE SEMUA WEB KLIEN (via curl)")
    print("=" * 62)
    results = []
    for name, site in SITES:
        print(f"\n▶ {name} — {site}")
        # 1) Refetch homepage no-cache
        c1, t1 = curl(site + "/?_cc=" + str(int(time.time())))
        print(f"   [homepage no-cache] -> HTTP {c1} ({t1:.2f}s)")
        # 2) Refetch wp-json (menghidupkan PHP/DB fresh)
        c2, t2 = curl(site.rstrip("/") + "/wp-json/?_cc=" + str(int(time.time())))
        print(f"   [wp-json no-cache]  -> HTTP {c2} ({t2:.2f}s)")
        # 3) Purge LiteSpeed header jika server LiteSpeed
        c3, t3 = curl(site.rstrip("/") + "/_lspurge=" + str(int(time.time())),
                      extra=["-H", "X-LiteSpeed-Purge: *", "-H", "X-LSCache-Control: no-cache"])
        print(f"   [litespeed purge]   -> HTTP {c3} ({t3:.2f}s)")
        results.append({"name": name, "site": site, "home": c1, "json": c2, "ls": c3})
        time.sleep(1)

    print("\n" + "=" * 62)
    print("RINGKASAN")
    print("=" * 62)
    ok = 0
    for r in results:
        # situs dianggap OK kalau setidaknya 1 endpoint 200/301
        good = any(x in (200, 301, 302, 403) for x in (r["home"], r["json"], r["ls"]))
        if good:
            ok += 1
        mark = "✅" if good else "⚠️"
        print(f"{mark} {r['name']:<16} {r['site']:<32} home={r['home']} json={r['json']} ls={r['ls']}")
    print(f"\nSelesai: {ok}/{len(results)} situs responsif. Cache ter-flush.")

if __name__ == "__main__":
    main()
