#!/usr/bin/env python3
"""DAS: pengawas ketersediaan + Lighthouse otomatis.
Cek tiap 60 detik; begitu situs hidup, jalankan Lighthouse untuk beranda dan satu halaman artikel."""
import json, os, subprocess, time, urllib.request, urllib.error

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/124 Safari/537.36"}
CHROME = "/home/mantapman/.cache/ms-playwright/chromium-1243/chrome-linux64/chrome"
LOG = f"{WS}/drafts/pemantauan_das.log"
HALAMAN = [("beranda", "https://dasindonesia.com/"),
           ("artikel-nissan", "https://dasindonesia.com/bengkel-spesialis-nissan-surabaya/")]


def catat(baris):
    with open(LOG, "a") as f:
        f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')}  {baris}\n")
    print(baris, flush=True)


def hidup(u):
    try:
        r = urllib.request.urlopen(urllib.request.Request(u, headers=UA), timeout=30)
        return r.status, len(r.read())
    except urllib.error.HTTPError as e:
        return e.code, 0
    except Exception:
        return 0, 0


catat("=== pemantauan dimulai ===")
mati_sejak = None
for putaran in range(240):          # maksimal 4 jam
    st, n = hidup("https://dasindonesia.com/")
    if st == 200 and n > 5000:
        if mati_sejak:
            catat(f"situs HIDUP lagi (mati sejak {mati_sejak}, sekitar {round((time.time()-mati_sejak)/60)} menit)")
            mati_sejak = None
        catat(f"beranda normal ({n} byte) — menjalankan Lighthouse")
        for nama, u in HALAMAN:
            keluar = f"{WS}/drafts/lh_{nama.replace('-', '_')}.json"
            perintah = ["npx", "--no-install", "lighthouse", u, "--preset=desktop",
                        "--only-categories=performance,seo,accessibility,best-practices",
                        "--throttling-method=provided", "--max-wait-for-load=150000",
                        "--output=json", f"--output-path={keluar}",
                        "--chrome-flags=--headless=new --no-sandbox --disable-dev-shm-usage --disable-gpu", "--quiet"]
            env = {**os.environ, "CHROME_PATH": CHROME}
            r = subprocess.run(perintah, env=env, cwd=WS, capture_output=True, text=True, timeout=900)
            ok = os.path.exists(keluar)
            catat(f"   lighthouse {nama}: {'selesai' if ok else 'gagal'} | {(r.stderr or '').strip()[-120:]}")
        break
    else:
        if not mati_sejak:
            mati_sejak = time.time()
            catat(f"⚠️ situs TIDAK merespons (status {st}) — pemantauan tiap 60 detik")
        time.sleep(60)
catat("=== pemantauan selesai ===")
