#!/usr/bin/env python3
"""DAS: baca hasil Lighthouse dan rangkum temuan yang bisa dikerjakan."""
import json, sys

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
BERKAS = sys.argv[1] if len(sys.argv) > 1 else f"{WS}/drafts/lh_das_desktop.json"
d = json.load(open(BERKAS))
print(f"== {BERKAS.split('/')[-1]} ==")
err = d.get("runtimeError")
if err:
    print("   GAGAL:", err.get("code"), str(err.get("message"))[:100])
    sys.exit(0)

print("SKOR:", {k: round((v.get("score") or 0) * 100) for k, v in d.get("categories", {}).items() if isinstance(v, dict)})
a = d.get("audits", {})

print("\n== metrik inti ==")
for k in ("first-contentful-paint", "largest-contentful-paint", "total-blocking-time",
          "cumulative-layout-shift", "speed-index", "server-response-time", "total-byte-weight",
          "dom-size", "mainthread-work-breakdown", "bootup-time"):
    x = a.get(k, {})
    if x:
        print(f"   {x.get('title', k):<44} {x.get('displayValue', '-')}")

print("\n== yang gagal / error ==")
for k, x in a.items():
    if x.get("score") == 0:
        print(f"   ✗ {x.get('title', k)[:70]}")
        det = x.get("details", {}) or {}
        for it in (det.get("items") or [])[:4]:
            ringkas = " | ".join(f"{kk}={str(vv)[:60]}" for kk, vv in it.items() if kk in
                                 ("url", "source", "node", "label", "explanation", "sourceLocation", "wastedBytes", "totalBytes"))
            if ringkas:
                print(f"        {ringkas[:150]}")

print("\n== peluang (ada penghematan) ==")
for k, x in a.items():
    det = x.get("details", {}) or {}
    ms = det.get("overallSavingsMs")
    by = det.get("overallSavingsBytes")
    if (ms or by) and x.get("score") is not None and x["score"] < 0.95:
        ket = []
        if ms:
            ket.append(f"{round(ms)} ms")
        if by:
            ket.append(f"{round(by/1024)} KB")
        print(f"   {x.get('title', k)[:56]:<58} {' · '.join(ket)}")

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

print("\n== gambar: apakah sudah optimal ==")
for k in ("uses-optimized-images", "uses-responsive-images", "offscreen-images", "modern-image-formats",
          "unsized-images", "image-alt", "efficient-animated-content"):
    x = a.get(k, {})
    if not x:
        continue
    det = x.get("details", {}) or {}
    print(f"   [{x.get('score')}] {x.get('title', k)[:56]:<58} {len(det.get('items') or [])} temuan")

print("\n== ringkasan jumlah temuan per audit ==")
for k, x in a.items():
    if x.get("score") is not None and x["score"] < 1 and not x.get("scoreDisplayMode") == "informative":
        n = len((x.get("details", {}) or {}).get("items") or [])
        if n and x["score"] < 0.9:
            print(f"   [{round(x['score']*100):>3}] {x.get('title', k)[:60]:<62} {n} temuan")
