#!/usr/bin/env python3
"""DAS: gali detail temuan Lighthouse yang bisa dikerjakan (console error, robots, tautan, gambar)."""
import json, sys

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
d = json.load(open(sys.argv[1] if len(sys.argv) > 1 else f"{WS}/drafts/lh_das_beranda.json"))
a = d.get("audits", {})


def tampil(judul, kunci, ambil=("url", "source", "description", "node", "label", "explanation")):
    x = a.get(kunci, {})
    if not x:
        return
    print(f"\n== {judul} (skor {x.get('score')}) ==")
    print(f"   {str(x.get('description'))[:170]}")
    det = x.get("details", {}) or {}
    for it in (det.get("items") or [])[:8]:
        bagian = []
        for k in ambil:
            if k in it and it[k] is not None:
                nilai = it[k]
                if k == "node" and isinstance(nilai, dict):
                    nilai = (nilai.get("snippet") or nilai.get("selector") or "")[:120]
                bagian.append(f"{k}={str(nilai)[:130]}")
        print("   ·", " | ".join(bagian)[:300])
    if det.get("url") and not det.get("items"):
        print("   url:", det["url"])


tampil("Error di console peramban", "errors-in-console")
tampil("robots.txt tidak sah", "robots-txt")
tampil("Tautan tidak bisa dirayapi", "crawlable-anchors")
tampil("Tautan tanpa keterangan", "link-text")
tampil("Gambar", "unsized-images")
tampil("Gambar lazy", "offscreen-images", ambil=("url", "totalBytes", "wastedBytes"))
tampil("Gambar belum optimal", "uses-optimized-images", ambil=("url", "totalBytes", "wastedBytes"))
tampil("Gambar tidak responsif", "uses-responsive-images", ambil=("url", "totalBytes", "wastedBytes"))
tampil("CSS tidak terpakai", "unused-css-rules", ambil=("url", "wastedBytes", "totalBytes"))
tampil("JS tidak terpakai", "unused-javascript", ambil=("url", "wastedBytes", "totalBytes"))
tampil("Skrip penghambat render", "render-blocking-resources", ambil=("url", "totalBytes", "wastedMs"))

print("\n== DOM & ukuran ==")
for k in ("dom-size", "total-byte-weight", "network-requests"):
    x = a.get(k, {})
    if x:
        print(f"   {x.get('title', k)}: {x.get('displayValue')}")

print("\n== 15 sumber daya terberat ==")
items = (a.get("network-requests", {}).get("details", {}) or {}).get("items", [])
for it in sorted(items, key=lambda z: -(z.get("transferSize") or 0))[:15]:
    print(f"   {round((it.get('transferSize') or 0)/1024):>6} KB  {it.get('resourceType', '?'):<9} {str(it.get('url'))[:95]}")

print("\n== skrip pihak ketiga ==")
x = a.get("third-party-summary", {})
for it in ((x.get("details", {}) or {}).get("items") or [])[:10]:
    print(f"   blocking {round(it.get('blockingTime') or 0):>6} ms | {round((it.get('transferSize') or 0)/1024):>5} KB | {str(it.get('entity'))[:60]}")
