#!/usr/bin/env python3
"""Halaman ringkasan KPI semua klien + render semua dasbor (index & per klien) jadi PNG."""
import asyncio, html, json, os, sys, time
from datetime import datetime

WS = "/home/mantapman/.hermes/profiles/atun/workspace"
DIR = f"{WS}/drafts/kpi"

# Render butuh /usr/bin/python3 (playwright ada di sana, bukan di python3 3.11).
# Kalau dijalankan dengan interpreter tanpa playwright, jalan ulang otomatis.
try:
    import playwright  # noqa: F401
except ImportError:
    if sys.executable != "/usr/bin/python3" and os.path.exists("/usr/bin/python3"):
        print(f"(render: pindah interpreter → /usr/bin/python3)")
        os.execv("/usr/bin/python3", ["/usr/bin/python3", os.path.abspath(__file__)] + sys.argv[1:])
    raise

ringkas = json.load(open(f"{DIR}/ringkasan_kpi.json"))
waktu = datetime.now().strftime("%d %B %Y, %H:%M WIB")

# Umur data: kapan ringkasan_kpi.json terakhir ditulis (bukan kapan gambar dibuat).
JSON_DATA = f"{DIR}/ringkasan_kpi.json"
umur_hari = (time.time() - os.path.getmtime(JSON_DATA)) / 86400
data_tanggal = datetime.fromtimestamp(os.path.getmtime(JSON_DATA)).strftime("%d %B %Y")
if umur_hari > 3:
    catatan_data = (f'<div class="peringatan"><strong>DATA BELUM DIPERBARUI.</strong> '
                    f'Angka di bawah berasal dari pengambilan terakhir {data_tanggal} '
                    f'({umur_hari:.0f} hari lalu). Token Google (Search Console &amp; GA4) mati '
                    f'sejak 8 Okt 2026 — laporan mingguan ini belum berisi data baru.</div>')
else:
    catatan_data = ''



def ang(p):
    try:
        return float(str(p).replace("%", "").replace("+", ""))
    except Exception:
        return 0.0


baris = ""
for k in sorted(ringkas, key=lambda x: -x["klik"]):
    d = ang(k["d_klik"])
    w_klik = "#0f9d58" if d > 1 else ("#d93025" if d < -1 else "#5f6368")
    w_pos = "#0f9d58" if (k["posisi"] or 99) <= 10 else ("#f9ab00" if (k["posisi"] or 99) <= 30 else "#d93025")
    baris += (f'<tr><td><strong>{html.escape(k["nama"])}</strong></td>'
              f'<td class="angka">{k["klik"]:,}</td>'
              f'<td class="angka" style="color:{w_klik}">{k["d_klik"]}</td>'
              f'<td class="angka">{k["tayang"]:,}</td><td class="angka">{k["ctr"]}%</td>'
              f'<td class="angka" style="color:{w_pos};font-weight:600">{k["posisi"]}</td>'
              f'<td class="angka">{k["sesi_total"]:,}</td><td class="angka">{k["organik"]:,}</td>'
              f'<td class="angka">{k["ai"]}</td><td class="angka">{k["kontak"]}</td></tr>')

htm = f"""<!DOCTYPE html><html lang="id"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1"><title>Ringkasan KPI Klien</title>
<style>
 body{{font-family:-apple-system,Segoe UI,Roboto,sans-serif;background:#f6f7f9;color:#202124;margin:0;padding:22px}}
 h1{{font-size:21px;margin:0 0 4px}} .sub{{color:#5f6368;font-size:12.5px;margin-bottom:18px}}
 table{{width:100%;border-collapse:collapse;background:#fff;border:1px solid #e3e6ea;border-radius:10px;overflow:hidden}}
 th,td{{padding:9px 11px;font-size:12.5px;text-align:left;border-bottom:1px solid #eef0f2}}
 th{{background:#fafbfc;color:#5f6368;font-weight:600;font-size:12px}} .angka{{text-align:right}}
 .peringatan{{background:#fce8e6;border:1px solid #f2b8b5;color:#a50e0e;font-size:12.5px;
   border-radius:8px;padding:10px 13px;margin:0 0 14px;line-height:1.45}}
 footer{{color:#5f6368;font-size:11.5px;margin-top:18px}}
</style></head><body>
<h1>Ringkasan KPI Semua Klien</h1>
<div class="sub">Sumber: Google Search Console (28 hari, dibanding 28 hari sebelumnya) + GA4 (90 hari) ·
 data terakhir {data_tanggal} · gambar dibuat {waktu}</div>
{catatan_data}
<table><thead><tr>
<th>Klien</th><th class="angka">Klik</th><th class="angka">Δ klik</th><th class="angka">Tayangan</th>
<th class="angka">CTR</th><th class="angka">Posisi</th><th class="angka">Sesi</th>
<th class="angka">Organik</th><th class="angka">AI</th><th class="angka">Kontak</th>
</tr></thead><tbody>{baris}</tbody></table>
<footer>Kolom "Kontak" = peristiwa klik WhatsApp/telepon yang terekam (90 hari). Angka nol berarti pelacakan konversi belum terpasang, bukan berarti tidak ada yang menghubungi.
Dasbor rinci per klien tersimpan sebagai berkas terpisah di folder yang sama.</footer>
</body></html>"""

open(f"{DIR}/kpi_semua_klien.html", "w").write(htm)
print(f"ringkasan dibuat: {DIR}/kpi_semua_klien.html")


async def render():
    from playwright.async_api import async_playwright
    berkas = [f"{DIR}/kpi_semua_klien.html"] + sorted(
        os.path.join(DIR, f) for f in os.listdir(DIR) if f.startswith("kpi_") and f.endswith(".html")
        and f != "kpi_semua_klien.html")
    async with async_playwright() as pw:
        br = await pw.chromium.launch()
        hal = await br.new_page(viewport={"width": 1180, "height": 1000}, device_scale_factor=2)
        for b in berkas:
            png = b.replace(".html", ".png")
            await hal.goto("file://" + b, wait_until="load", timeout=60000)
            await hal.wait_for_timeout(900)
            await hal.screenshot(path=png, full_page=True)
            print(f"   {os.path.basename(png)} ({round(os.path.getsize(png)/1024)} KB)")
        await br.close()


asyncio.run(render())
print("selesai")
